0
1

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 5 years have passed since last update.

range

Last updated at Posted at 2019-06-19

rangeを使うとfor文を簡単に書ける。
mapでも同じことができるというのを併記します。

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

	for i := 0; i < len(l); i++ {
		fmt.Println(i, l[i])
	}
	//rangeを使って書き換え
	for i, v := range l { //vは任意
		fmt.Println(i, 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)
	}
}

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?