Pointer types

March 23, 2023

After the long discussion of the details and nuances of struct types, we have a simple topic: Pointers!

Well, maybe it’s not that simple. There are a lot of subtleties that go into the proper use of pointers. But from a specification standpoint, it’s simple. This is the entirety of the section:

Pointer types

A pointer type denotes the set of all pointers to variables of a given type, called the base type of the pointer. The value of an uninitialized pointer is nil.

PointerType = "*" BaseType .
BaseType    = Type .
*Point
*[4]int

The most important thing to note here is that pointers always have a base type, and that the base type may be any other type. Including another pointer. Or an interface:

	var x int
	var y *int
	var z **int
	var youMustBeKidding **********int
	fmt.Println(x, y, z, youMustBeKidding) // Prints: 0 <nil> <nil> <nil>

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this

Related Content

Zero values of slices and maps

Composite literals … Note that the zero value for a slice or map type is not the same as an initialized but empty value of the same type. Let’s look at examples so we can understand exactly what is being stated here. Recall that when you declare a variable of a given type, the default value is the zero value for the type: var s1 []string // Zero value for slice var m1 map[string]int // Zero value for map What the spec is telling us is that the zero value of a slice or map is not the same as an initialized, but empty, slice or map:

Taking the address of literals

Composite literals … Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal’s value. var pointer *Point3D = &Point3D{y: 1000} This particular feature of the language is immensely useful. Without it, the above code snippet would become much longer: var point Point3D = Point3D{y: 1000} var pointer *Point3D = &point In fact, this is the exact situation we are in for non-composites.

Limitations on methods

Today I’ll be love coding again. I hope you can join me! I’ll be working on the backlog for my open-source CouchDB SDK, https://kivik.io/ to add a long-missing feature. Join me to see how many mistakes a senior Go dev makes while coding. Method declarations … A receiver base type cannot be a pointer or interface type and it must be defined in the same package as the method. This tiny sentence has three distinct cases to consider.