Itβs a named collection of fields to store related data.
Struct can be defined inside or outside of a function. When defined inside a function, its scope is that function.
Init
Different ways to initialize the struct:
If you donβt provide a value for the field inside a struct, it will be initialized with a zero value for its type.
When using a pointer to a struct, Go treats p.X
treats the same as (*p).X
(with explicit dereference).
Embedding
We have a type A, with a field year and a method Greet. We have a second type, B which embeds an A, thus callers see Bβs methods overlaid on Aβs because A is embedded, as a field, within B, and B can provide its own Greet method, obscuring that of A.
But embedding isnβt just for methods, it also provides access to an embedded typeβs fields. As you see, because both A and B are defined in the same package, B can access Aβs private year field as if it were declared inside B.
But:
In this example we have a Cat type, which can count its number of legs with its Legs method. We embed this Cat type into a new type, an OctoCat, and declare that Octocats have five legs. However, although OctoCat defines its own Legs method, which returns 5, when the PrintLegs method is invoked, it returns 4.
This is because PrintLegs is defined on the Cat type. It takes a Cat as its receiver, and so it dispatches to Catβs Legs method. Cat has no knowledge of the type it has been embedded into, so its method set cannot be altered by embedding.
Thus, we can say that Goβs types, while being open for extension, are closed for modification. https://dave.cheney.net/2016/08/20/solid-go-design
Anonymous struct
They are useful for:
- When you translate external data into a struct or a struct into external data (like JSON or Protocol Buffer) - unmarshalling and marshalling data respectively.
- Tests, for example structs for table-driven tests.
Comparison
Structs are comparable when it contains only comparable fields.
Structs of different types canβt be compared, even if they have the same set of fields. But if one of the struct is anonymous, you can compare them.
Conversion
Instances of a different structs type with the same set of fields can be converted.
Struct tags
You can provide annotations for each field on the struct: