Skip to content

Structs

Intermediate · Types & Methods

A struct groups named fields into a composite type. Construct with field names (T{Field: v}), access with a dot. Go favors composition via embedding (declaring a type without a field name) over inheritance, and you attach behavior with methods.

Define the struct’s fields.

Show hint
Structs are created using the `type structName struct {}` syntax.
Fields inside the brackets must have their types declared along with their names.

Source

Embed a struct instead of adding a plain field.

Show hint
Embedding a struct is done using just the struct name.
After embedding, fields can be accessed directly through the base struct without specifying the full path, but you can if needed.

Source

Attach a method to a struct.

Show hint
Add a function to a struct by defining it as follows:
func (s *StructHere) doSomething() {
}

Source