Beyond the basics

Go has pointers but not pointer arithmetic. You cannot use a pointer variable to walk through the bytes of a string.


Go For C++ Programmers – Go Authors

In this chapter we delve deeper into the language.

Go has pointers. There is however no pointer arithmetic, so they act more likereferences than pointers that you may know from C. Pointers are useful. Rememberthat when you call a function in Go, the variables arepass-by-value. So, for efficiency and the possibility to modify a passed value in functions we have pointers.

You declare a pointer by prefixing the type with an ‘’: var p int. Now pis a pointer to an integer value. All newly declared variables are assignedtheir zero value and pointers are no different. A newly declared pointer, orjust a pointer that points to nothing, has a nil-value . In otherlanguages this is often called a NULL pointer in Go it is just nil. To makea pointer point to something you can use the address-of operator (&), which we demonstrate here:

  1. var p *int
  2. fmt.Printf("%v", p) 1
  3. var i int 2
  4. p = &i 3
  5. fmt.Printf("%v", p) 4

This 1 Prints nil. Declare 2 an integer variable i. Make p point 3to i, i.e. take the address of i. And this 4 will print something like0x7ff96b81c000a. De-referencing a pointer is done by prefixing the pointervariable with *.

As said, there is no pointer arithmetic, so if you write: p++, it isinterpreted as (p)++: first reference and then increment thevalue.