Array and slice confused me a bit when learning Golang and wanted to share things that I learned along the way.
Array
Developers loves fruits 🍎 so we make an array of fruits
- Arrays size is defined and cannot be resized.
- playground
var a [2]string // define an array of fixed size.
a[0] = "apple" // assign value to the array at index 0
a[1] = "banana"fmt.println(a) // Print the array
Slice
- slice is a reference to an array
- slice is dynamically-sized
- slice is more useful than an array
- playground
Literals// this will create an array of size 3
array := [3]bool{true,false,true} // 1. this will create an array
// 2. slice will be created referencing the array in step 1slice := []bool{true,false,true}
Slice has a length and capacity
- length, is the number of elements it contains
- capacity, is the number of elements in the underlying array for the slice.
Make function
- slice can be created by
make
function - make signature from the official documentation
make( type, size, capacity)-> type : type of slice we want to make, for example []int
-> size : specifies the length
-> capacity : a number no smaller than size, it is the size of an underlying array. If not specified then it is same as size (2nd parameter).