Stage 1 · Code
Functions & Composite Types
Structs
Group related fields into named types — Go's way to model records, entities, and domain objects without classes.
Defining Structs
A struct is a composite type that groups fields together under one name. Each field has a name and a type. Structs replace classes in Go — they hold data, and you attach behaviour separately using methods.
Creating and Using Structs
You can create a struct with positional or named field initialization. Named initialization is almost always preferred — it is self-documenting and unaffected by field reordering.
Positional initialization Server{"host", 443, true, 1000} breaks silently when you add, remove, or reorder fields. Named initialization Server{Host: "host", Port: 443} survives field changes and is self-documenting. Make it a habit.
Struct Embedding
Embedding includes one struct type inside another without giving it an explicit field name. The embedded type's fields and methods are promoted: you can access them directly on the outer struct.
Comparing Structs
Two structs of the same type are equal if all their fields are equal. Structs that contain non-comparable fields (like maps or slices) cannot be compared with ==.
Anonymous Structs
You can define a struct without giving it a name. Anonymous structs are useful for small, local data shapes — especially in tests and one-off groupings.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.