Last active
August 29, 2015 14:14
-
-
Save giwa/a4e2961f3fe379c50e14 to your computer and use it in GitHub Desktop.
Go by Example: Range ref: http://qiita.com/giwa@github/items/53f807036c104c4ca009
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
// ここではsliceの中の数字を合計するためにrangeを使います。 | |
// arrayでも同じように動きます。 | |
nums := []int{2, 3, 4} | |
sum := 0 | |
for _, num := range nums { | |
sum += num | |
} | |
fmt.Println("sum:", sum) | |
// sliceとarrayのrangeはそれぞれのエントリーのindexと値を提供します。 | |
// 上記のものは、indexを必要としておらず、blankを示す _で無視しています。 | |
// indexを走査する用途も実際にはあります。 | |
for i, num := range nums { | |
if num == 3 { | |
fmt.Println("index:", i) | |
} | |
} | |
// mapにrangeを適用する場合は、key/valueのペアでイテレーションします。 | |
kvs := map[string]string{"a": "apple", "b": "banana"} | |
for k, v := range kvs { | |
fmt.Printf("%s -> %s\n", k, v) | |
} | |
// stringにrangeを適用する場合は、Unicodeの数字をイテレーションします。 | |
// 最初の値は文字のindexで、2つ目の値は文字(unicodeのその字を表す数字)そのものです。 | |
for i, c := range "go" { | |
fmt.Println(i, c) | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
// ここではsliceの中の数字を合計するためにrangeを使います。 | |
// arrayでも同じように動きます。 | |
nums := []int{2, 3, 4} | |
sum := 0 | |
for _, num := range nums { | |
sum += num | |
} | |
fmt.Println("sum:", sum) | |
// sliceとarrayのrangeはそれぞれのエントリーのindexと値を提供します。 | |
// 上記のものは、indexを必要としておらず、blankを示す _で無視しています。 | |
// indexを走査する用途も実際にはあります。 | |
for i, num := range nums { | |
if num == 3 { | |
fmt.Println("index:", i) | |
} | |
} | |
// mapにrangeを適用する場合は、key/valueのペアでイテレーションします。 | |
kvs := map[string]string{"a": "apple", "b": "banana"} | |
for k, v := range kvs { | |
fmt.Printf("%s -> %s\n", k, v) | |
} | |
// stringにrangeを適用する場合は、Unicodeの数字をイテレーションします。 | |
// 最初の値は文字のindexで、2つ目の値は文字(unicodeのその字を表す数字)そのものです。 | |
range on strings iterates over Unicode code points. The first value is the starting byte index of the rune and the second the rune itself. | |
for i, c := range "go" { | |
fmt.Println(i, c) | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run range.go | |
sum: 9 | |
index: 1 | |
a -> apple | |
b -> banana | |
0 103 | |
1 111 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment