Pointing to Go?—?The Go Pointer Type
Vladimir Vivien
Software Engineer | Build stuff in Go | Kubernetes Contributor | LinkedIn Instructor
In my introductory write up on Go types, I did a (rather length) summarized walk-through of the basic and composite types in Go (read it here if you need a refresher). Continuing with this theme, this write up discusses the pointer type: how to create and initialize pointer types.
The Pointer Type
The pointer type in Go is used to point to a memory address where data is stored. Similar to C/C++, Go uses the * operator to designate a type as a pointer. The following snippet shows several pointers with different underlying types.
The code snippet above declares each variable as a pointer to its associated type:
- variables valPtr and countPtr are pointers to their respective primitive types float32 and int
- variables prsn and matrix are declared as pointers to their respective composite types person and [1024]int.
- Lastly, variable row is a slice of pointers to elements to type int64.
Each pointer stores an address which points to a memory location where a value, of the indicated underlying type, is stored. Go does not allow pointer arithmetic and, as you have come to expect with Go’s strict type system, each pointer type is unique. Meaning, the following will not compile.
The Address Operator
Go uses the & (ampersand) operator to return the address of a variable. For instance, the following uses the address operator in expressions that return memory locations for associated values.
The two variables valPtr and scorePtr, in the pervious code snippet, are assigned memory addresses with expressions &val and &score respectively. The second portion of the code snippet shows function printId(id *string)that takes a pointer as its sole parameter. It is invoked with the address value &uid as its argument.
Read on ...
There is much more to to Go pointers! Continue to read the full write on @Medium - https://medium.com/learning-the-go-porgramming-language/pointing-to-go-the-go-pointer-type-a3c3f587592f