0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

go修行6日目 for文とか

Posted at

for


package main

import "fmt"

func main() {
	for i := 0; i < 10; i++ {
		if i == 3 {
			fmt.Println("continue")
			// ループ内のcontinue以降は実行されず、次のループへ行く
			continue
		}

		if i > 5 {
			fmt.Println("break")
			// ループ終了
			break
		}
		fmt.Println(i)
	}

	// 省略版
	sum := 1
	for sum < 10 {
		sum += sum
		fmt.Println(sum)
	}
	fmt.Println(sum)
}
0
1
2
continue
4
5
break
2
4
8
16

range

  • 要素数分ループ

package main

import "fmt"

func main() {
	l := []string{"python", "go", "java"}

	for i := 0; i < len(l); i++ {
		fmt.Println(i, l[i])
	}

	// 短縮版 lの中身のインデックスを入れてくれる
	for i, v := range l {
		fmt.Println(i, v)
	}

	// vだけ使いたい場合
	for _, v := range l {
		fmt.Println(v)
	}

	// map型
	m := map[string]int{"apple": 100, "banana": 200}

	for k, v := range m {
		fmt.Println(k, v)
	}

	// keyだけ取り出す
	for k := range m {
		fmt.Println(k)
	}

	// valueだけを取り出す
	for _, v := range m {
		fmt.Println(v)
	}
}
0 python
1 go
2 java
0 python
1 go
2 java
python
go
java
apple 100
banana 200
apple
banana
100
200

switch文

package main

import "fmt"

func getOsName() string {
	return "windows"
}
func main() {
	// os := "windows"
	os := getOsName()
	switch os {
	case "mac":
		fmt.Println("Mac")
	case "windows":
		fmt.Println("Windows")
		// defaultなくても大丈夫
	default:
		fmt.Println("Default")
	}
}
Windows
package main

import (
	"fmt"
	"time"
)

func getOsName() string {
	return "linux"
}
func main() {
	// switch文の中だけ変数が有効 短縮版
	switch os := getOsName(); os {
	case "mac":
		fmt.Println("Mac")
	case "windows":
		fmt.Println("Windows")
	default:
		fmt.Println("Default", os)
	}

	// timeオブジェクトのメソッド部分も利用できる
	t := time.Now()
	fmt.Println(t.Hour())
	switch {
	case t.Hour() < 12:
		fmt.Println("Morning")
	case t.Hour() < 17:
		fmt.Println("Afternoon")
	}
}
Default linux
8
Morning
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?