They are somewhat similar to object references in JS and other languages, but not quite. Pointer are more powerful (and thus, more dangerous) than references. Consider the following JS code.
var a = {foo: true};
var b = a;
a.foo = false;
console.log(b); // Output: "Object { foo: false }"
Both a
and b
here are like pointer. When you do b = a
you don't clone an object, you make b
refer (or point if you will) to the same object as a
. In Go you can do both:
type T struct { Foo bool }
a := T{Foo: true}
b := a
a.Foo = false
fmt.Println(b) // b is a copy, so it didn't change. Prints "{true}".
pa := &T{Foo: true}
pb := pa
pa.Foo = false
fmt.Println(pb) // pb points to the same struct as pa, so it prints "&{false}"
Playground
The important difference is that in JS you can't actually replace the object inside a function.
var a = {foo: true};
(function(x) { x = {foo: false} })(a);
console.log(a); // Output: "Object { foo: true }"
In Go you can do it just fine:
pa := &T{Foo: true}
func(p *T) { *p = T{Foo: false} }(pa)
fmt.Println(pa) // Output: &{false}
Playground
Another difference is that you can make pointers to not just structs, but any type, including pointers.