// specified length of 5 elements arr1 := [5]int{4,5,6,7,8} // inferred length arr2 := [...]int{4,5,6,7,8} // string array var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
range
The range
form of the for loop
iterates over a slice
or map
.
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 numbers = []int{1, 2, 4, 8, 16, 32, 64, 128} // using just the values func main() { for _, v := range pow { fmt.Printf("%d ", v) } } // using both value and index func main() { for i, v := range numbers { fmt.Printf("index: %d, value: % \n", i, v) } }
_
)_
in index
position of range
is a way of declaring a variable you won't use
slices
moduleimport "slices" things := []string{"foo", "bar", "baz"} slices.Contains(things, "foo") // true
Byte
ArraybyteArr := []byte("Hello, Gophers!")