2D Arrays and Slices in Go

Advertisement

Advertisement

Two dimensional arrays and slices are useful for many situations. When creating an array in the Go programming language it is automatically initialized to the empty state, which is usually a 0. Arrays cannot be expanded. Arrays live in the stack and take up space in the compiled executable. Arrays are also passed by copy whereas slices pass pointers. Slices require a little more initialization at first but are more versatile. You can grab subsets of the arrays if needed, access elements directly, or expand the slices. Slices are thin wrappers around arrays and hold pointers to the array. They are initialized during run time and live in the heap.

Arrays

Try it in the Go Playground.

package main

import "fmt"

func main() {
// Initialize a 2D array
var grid [10][4]int
fmt.Println(grid)

// Another way to initialize 2D array
gridB := [6][3]int{}
fmt.Println(gridB)
}

Slices

Try it in the Go Playground.

package main

import "fmt"

func main() {

numRows := 10

// Initialize a ten length slice of empty slices
grid := make([][]int, numRows)

// Verify it is a slice of ten empty slices
fmt.Println(grid)

// Initialize those 10 empty slices
for i := 0; i < numRows; i++ {
grid[i] = make([]int, 4)
}

// grid is a 2d slice of ints with dimensions 10x4
fmt.Println(grid)
}

Advertisement

Advertisement