Pointer#
Go is technically a pass-by-value language. However, certain types behave as if they are pass-by-reference because they are implemented using pointers under the hood.
Types with Pointer Implementation#
The following types are implemented as pointers or contain pointers in their internal headers. When passed to a function, the pointer is copied (passed by value), but it still points to the same underlying data.
slicemapfunctionchannelinterface
Slice Caveat#
While you can modify the elements of a slice passed to a function, you cannot change its length (eg. by append) such that the change is reflected in the caller. This is because the slice header (which contains the length and capacity) is passed by value.
Zero Value#
The zero value for these types is nil.
eg.
var s []int // nil
var m map[int]int // nil
var f func() // nil
var c chan int // nil
var i interface{} // nilnew#
The built-in function new creates a pointer variable. It returns a pointer to a zero-value instance of the provided type.
eg.
var x = new(int)
fmt.Println(x == nil) // false
fmt.Println(*x) // 0Note that new is rarely used in practice. For structs, the composite literal &T{} is preferred as it allows initializing fields.