A pointer is a variable that holds the memory address of another value, instead of the value itself.
In Go
&xtakes the address ofx;*preads the value at the address.- A pointer’s zero value is
nil, and reading*pwhenp == nilcrashes the program (panic). - There is no pointer arithmetic (as in C), which removes a whole class of bugs.
Go always passes arguments by value (a copy). For a function to change the original, pass a pointer:
func double(n int) { n *= 2 } // changes the copyfunc doublePtr(n *int) { *n *= 2 } // changes the original
x := 21double(x) // x is still 21doublePtr(&x) // x is now 42Pointers also avoid copying large structs and allow methods that change the receiver (func (u *User) Rename(...)).
In Java
Java has no explicit pointers, but every object variable is a reference (in practice, a managed pointer). And Java also passes everything by value: what gets passed is a copy of the reference.
void rename(User u) { u.setName("Ana"); } // changes the original objectvoid replace(User u) { u = new User("Ana"); } // only swaps the local copy of the referenceThat is why you can change an object you receive, but you can’t write a swap(a, b) that swaps the caller’s variables. An empty reference is null, the equivalent of Go’s nil.
See also: Pointers in Go and Variables and constants.