Advanced Go Coding — struct{}

In-depth implementation, application and best practices of Go struct{}

Stefanie Lai

--

from Unsplash

Unlike common structures in Go, struct{} is an empty structure, which contains no fields or data and is a special zero-value structure that occupies no memory, making it extremely lightweight in memory management and applicable to many specific scenarios.

Internal Implementation

In Go’s internal implementation, a structure is defined via a type descriptor.

Type Descriptor

In Go compiler, type descriptor is a data structure for describing type information that and stores the metadata of the type, such as fields, methods, size, alignment, etc. For structure types, the descriptor includes not only the structure size, but also the field’s number, name, type, location information, etc.

The implementation of the descriptors lies in the reflect package of the Go source code. The rtype structure in the reflect package is the basis for describing types and the base class of all type descriptors. And structType is used to describe structure types in Go as follows.

type structType struct {
rtype
pkgPath name
fields []structField
}

--

--