go slice and array
tags: learning go diff-between programming
questions
- what’s the difference between slice and array in go?
- can i create slice without creating an array?
content
An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array. → A Tour of Go
- how to understand flexible view?
array declaration needs a size, and a fixed size of memory is allocated to the array:
myArr := [2]int{1, 2}
fmt.Printf("%T", myArr) // prints out [2]intA slice does not store any data, it just describes a section of an underlying array. → A Tour of Go | Slices are like references to arrays
- slices are like references to arrays
- if a slice changes the value of its underlying array, other slices that reference that array will see the change
myArr := [5]int{1, 2, 3, 4, 5}
slice1 := myArr[1:3]
slice2 := myArr[2:4]
slice1[1] = 10
fmt.Println("slice1", slice1) // [2, 10]
fmt.Println("slice2", slice2) // [10, 4]Note
in go, we never really work with arrays directly. almost always deal with slices.