Go-range

提供:Dev Guides
移動先:案内検索

移動-範囲

*range* キーワードは *for* ループで使用され、配列、スライス、チャネル、またはマップの項目を反復処理します。 配列とスライスの場合、アイテムのインデックスを整数として返します。 マップでは、次のキーと値のペアのキーを返します。 範囲は、1つまたは2つの値を返します。 範囲式の左側で1つの値のみが使用されている場合、それは次の表の最初の値です。
Range expression 1st Value 2nd Value(Optional)
Array or slice a [n]E index i int a[i] E
String s string type index i int rune int
map m map[K]V key k K value m[k] V
channel c chan E element e E none

次の段落は、範囲を使用する方法を示しています-

package main

import "fmt"

func main() {
  /*create a slice*/
   numbers := []int{0,1,2,3,4,5,6,7,8}

  /*print the numbers*/
   for i:= range numbers {
      fmt.Println("Slice item",i,"is",numbers[i])
   }

  /* create a map*/
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo"}

  /* print map using keys*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

  /* print map using key-value*/
   for country,capital := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",capital)
   }
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo