Go - Versus

Last Updated: 2024-01-28

:= vs =

k := 1 is equivalent to var k int = 1:

  • no need to specify type when using :=
  • := construct can only be used inside a function, while a var statement can be at package or function level.
  • constants cannot be declared using :=, it has to use const keyword: const name = "foo".

make vs new

Go has a special make function that can be used to initialize channels, slices, and maps.

  • make is able to allocate variable memory and returns an instance of the provided type.
  • new can only initialize empty instances, and returns a pointer of the provided argument.
// returns a slice with 3 `0`s
s1 := make([]int, 3)
// returns a pointer to an empty slice
s2 := new([]int)

fmt.Println(s1)     // [0 0 0]
fmt.Println(s2)     // &[]

array vs slice

Slice: Under the covers, it is a struct value holding a pointer and a length

type sliceHeader struct {
    Length        int
    ZerothElement *byte

Use make to create a slice: it allocates a new array and creates a slice header to describe it, all at once.

How to tell slice from array

a := [4]int{3, 4, 5, 6}
b := a[:]
fmt.Printf("%T %T\n", a, b) // [4]int []int
fmt.Println(reflect.TypeOf(a).Kind(), reflect.TypeOf(b).Kind()) // array slice

vendor vs third-party

Many Go projects have both a vendor folder and a third-party folder (like Kubernetes).

They are all external dependencies, the difference is that vendor folder managed by the go mod vendor command, the dependencies can be specified in go.mod; while third-party is not managed automatically.