From 53104e83c21ac400850d5c58f3ea41843a7afd9b Mon Sep 17 00:00:00 2001 From: asandikci Date: Wed, 12 Jul 2023 16:04:57 +0300 Subject: [PATCH] Range --- 2moretypes/range.go | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 2moretypes/range.go diff --git a/2moretypes/range.go b/2moretypes/range.go new file mode 100644 index 0000000..f67177d --- /dev/null +++ b/2moretypes/range.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "reflect" +) + +func main() { + fmt.Println("Range form of the for loof iterates over a slice or map") + fmt.Println("When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index") + + var primes = []int{2, 3, 5, 7, 11, 13, 17} + + fmt.Printf("%p, %p, %p, %p\n", &primes, primes, &primes[0], &primes[1]) + fmt.Printf("%s, %s, %s\n\n", reflect.TypeOf(primes).Kind(), reflect.TypeOf(&primes).Kind(), reflect.TypeOf(&primes[0]).Kind()) + + for i, v := range primes { + fmt.Printf("%d: %d\n", i, v) + fmt.Printf("POINTER: %p\n\n", &v) // v is just a copy !!! + v = 10 // This line has NO impact + } + fmt.Println(primes) + + fmt.Printf("\n\n") + fmt.Println("You can skip the index OR value by assigning to _") + + // for i, _ := range varname + // for _, value := range varname + + pow := make([]int, 10) + for i := range pow { // i is INDEX here! not value of pow!!! + pow[i] = 1 << i + } + + for _, value := range pow { + fmt.Printf("%d\n", value) + } + +}