Structs in Go
Learn how structs work in Go.
The array data type in Go lets you store a collection of primitive variables.
Review the code below. The prices
variable is an array of length 3 and contains integer values declared within the {}
brackets. We assign new values to the first and second indices, and then we print the array.
package main
import "fmt"
func main() {
var prices [3]int = [3]int{1, 2, 3}
prices[0] = 4
prices[1] = 5
fmt.Println(prices)
}
The output is:
[4 5 3]
The shorthand declaration works with arrays too. The code snippet below creates an array of length 3 with three string values.
package main
import "fmt"
func main() {
flavors := [3]string{"Vanilla", "Chocolate", "Strawberry"}
fmt.Println(flavors)
}
The length of arrays are not mutable. If you create an array of length 5 you cannot change it later. This may seem awkward at first glance but it serves a purpose when you wish to specify very detailed memory allocation in your program.
Other things to know:
[5]int
and [10]int
are different array types.Arrays in Go are not widely used in Go programming. However, they do form the building block for slices.
Slices in Go are like Lists in Python. They’re commonly used to store a collection of variables of the same type.
Declaring a slice is quite similar to declaring an array except you don’t include a number inside the []
brackets.
package main
import "fmt"
func main() {
numbers := []int{20, 14, 15, 25, 8}
fmt.Println(numbers)
}
The output is:
[20 14 15 25 8]
You can retrieve values at certain indices, change their value, and append values to the slice as well.
In the example below, we create a numbers
slice and then assign new values to indices 0 and 1. The append()
function is used to append new values to a slice. However, it doesn’t modify the original slice but returns a new slice that is then assigned to the original variable numbers
.
package main
import "fmt"
func main() {
numbers := []int{20, 14, 15, 25, 8}
numbers[0] = 18
numbers[1] = 12
numbers = append(numbers, 3)
fmt.Println(numbers)
}
The output is:
[18 12 15 25 8 3]
Slices allow you to select ranges within them. This is similar to how Lists work in Python.
In the example below, a slice numbers
is created. A second slice some_numbers
is created by taking a range of values numbers
. In this case, we retrieve the values at indices 1, 2, and 3. The second number, 4
, is not inclusive.
package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5, 6}
some_numbers := numbers[1:4]
fmt.Println(some_numbers)
}
The output is:
[2 3 4]
Selecting everything from index 2 onward would look like:
numbers[2:]
Selecting everything up to and including index 3 would look like:
numbers[:4]
In this post we looked at the basics of creating and working with arrays and slices in Go. Arrays are a less common form of storing values but they are what slices use behind the scenes.
Check out the Go page for more lessons on programming in Go.