Andrew's Digital Garden

Structs in Go

A struct is an aggregate data type. It is composed of zero or more fields. A field is like a variable: it represents a value of a given type. If you need to include a field of the same type as the struct itself, use a pointer instead. A struct makes it possible to treat a collection of values as a single entity. A struct value can be copied, passed to functions, stored, and so on, like any other value. Structs are comparable if each of their fields are comparable.

type Planet struct { Name string Mass int64 }

Structs can be initialised with a literal, much like other types. When declaring multiple fields, the names and values can be used. This allows omission of some fields, and in any order. If not using the names of the fields, every field must have a corresponding value, and the order dictates the value mapping.

mars := Planet{ Name: "Mars", } mars := Planet{"Mars", 20}

Values can be accessed through dot notation (mars.Name), which also works for pointer values without any change in syntax. Private and public fields are based on the capitalisation, see [[20200720101212-go-private]]

Structs are passed to functions by value, i.e. they are copied. For large structs, pointer parameters may be more efficient. [[20200704153829-go-receivers]]

[[20200720142621-go-struct-embedding]] [[20210219145001-go-struct-nil]]

[[go]] [[structs]]

Structs in Go