Arrays and Slices in Go
Arrays
In Go, arrays have a fixed length. No element can be removed or added after declaration. However, individual elements of an existing array can be modified. An arrays length is part of its type. You specify them at the start or it is inferred from the initial value that was given.
array := [2]int{3,4}
fmt.Println(array) // Outputs: [3,4]
In the example above, an array of type int
is created with 2
values.
array := [3]string{"fizz", "buzz"}
fmt.Println(array) // Outputs: [fizz buzz]
// way to initialize array by avoiding specifying length.
array := [...]string{"fizz", "buzz"}
fmt.Println(array) // Outputs: [fizz buzz]
How to access specific elements of a go array
array := [2]int{3,4}
fmt.Println(array[0]) // Outputs: 3
fmt.Println(array[1]) // Outputs: 4
Now changing the second value in the array,
array := [2]int{3,4}
array[0] = 1
fmt.Println(array) // Outputs: [1,4]
Initialize arrays halfway and using a range.
array := [2]int{} // [0,0]
array2 := [3]int{} // [0,0,0]
array3 := [3]int{1,2} // [1,2,0]
// specify specific positions of the array to be initialized.
// syntax: position: value
array4 := [3]int{0:1, 2:8} // [10,0,8]
Slices
Wait ? How do i have a non-fixed length array ? We use slices.
Slice holds a reference to an array. Here is how to make one.
Slice literals
// this creates an array
array := [3]int{1,2}
// if you dont mention the length, It creates an array. then makes a slice that reference it
slice := []int{1,2}
Slice from arrays
Reference a parts of an array using slices. If the slice is then modified, the underlying array also changes. Any other slices which reference the same array also will see a value change.
users := [4]string{
"Admin",
"Customer",
"Staff",
"Superuser",
}
a := names[0:1]
b := names[1:3]
fmt.Println(a, b) // Outputs: [Admin] [Customer Staff]
b[0] = "Manager"
fmt.Println(users) // Outputs: [Admin, Manager, Staff, Superuser]
How to find the length and capacity of a go slice
slice := []int{1,2}
fmt.Println(len(slice)) // Outputs: 2
fmt.Println(cap(slice)) // Outputs: 2
How do I make a slice with a 1000 elements ?
We use make()
slice := make([]int, 1000)
fmt.Println(slice) // Outputs: [ 0 0 0 0 0 0 .........]
fmt.Println(len(slice)) // Outputs: 0
// specify capacity with third argument
slice2 := make([]int, 0, 5) // length 0, capacity for 5 elements
fmt.Println(len(slice2)) // Outputs: 0
fmt.Println(cap(slice2)) // Outputs: 5
How to append to a slice
The function append
is used to add elements to the end of a slice.
the function returns a slice with existing values and newly added value at the end.
slice := []int{1,2}
fmt.Println(slice) // Outputs: [1 2]
s = append(s, 3)
fmt.Println(slice) // Outputs: [1 2 3]
How to loop over a slice, array
The range
keyword is used to iterate over a slice.
Here i is the index and v is the element at that index
pow := []int{1,2,3,4}
for i, v := range pow {
fmt.Println(i) // 0, 1, 2, 3
fmt.Println(v) // 1, 2 ,3, 4
fmt.Printf(v*2) // 2, 4, 6, 8
}