Golang Tips and Tricks

Published on
Authors

As I learn more about the go language, some tips and tricks become apparent. I plan to record them here for reference purposes and also to reinforce them in my mind. This is a continuous process hopefully.

Shortcut to defining the number of items in an array

In golang, defining an array is usually done this way:

var myArray = [4]int{1,4,5,3}

But if you immediately instantiate the array with values, you can use three dots ... in place of the array size to imply that the size of the array is equal to the number of values passed during instantiation. Our expression becomes:

var myArray = [...]int{1,4,5,3}

Slice Capacity

Slices like the name implies, are a slice of something - arrays, and this means their sizes can differ from the underlying array.

mySlice := make([]int, 3, 10)
fmt.Println(len(mySlice)) // 3
fmt.Println(cap(mySlice)) // 10

mySlice2 := make([]int, 3)
fmt.Println(len(mySlice2)) // 3
fmt.Println(cap(mySlice2)) // 3

When we create a slice with the make function it takes an optional third parameter which defines the maximum size its underlying array can be. The cap function tells the size of a slice's underlying array.

Append is a variadic function

Citing wikipedia

a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.

In this case, it means that when you add items to a slice with the append function, every other parameter passed to it after the first (which is the slice), is added to the slice.

mySlice := []int{}
mySlice = append(mySlice, 4, 5, 6, 7)

fmt.Println(mySlice) // [4 5 6 7]

Concatenating slices with the "spread" operator

The three dots notation ..., called the spread operator in Javascript, can be used to concatenate slices but only when passed into a variadic function.

slice := []int{5}
slice1 := []int{56}

slices := append(slice, slice1...)
fmt.Println(slices) // [5, 56]