The Go Pointer Magic

Interesting Go pointer conversion

Stefanie Lai
CodeX

--

Go is a language with the pointer type, by which we can

  • Pass pointer into a function and update value in-place.
  • Add methods to a struct as (* T) A, which is different from (T) A().

However, the pointer is type-safe in Go, meaning that there are such restrictions of the pointer.

  • Different types of pointers are unconvertible.
  • Pointer type cannot be used for calculation.
  • Pointer types cannot be compared, either == nor !=.
  • No mutual assignment between different pointer-type variables.

For example, *int cannot be converted to *int32in the following code.

func main() {
i := int32(1)
ip := &i var iip *int8 = (*int8)(ip)
}
// cannot convert ip (type *int) to type *int32

Therefore, the only function of the pointer in Go is to point to the value’s memory address. This restriction improves code safety, simplifies usage, ultimately improving the overall robustness. But Go does provide a related workaround, among which uintptr and unsafe.Pointer are the most important types.

unsafe.Pointer

--

--