The Analogy: The Machined Housing
A camera housing is not a bag containing a lens mount, a sensor tray and a battery bay. It is one solid block of aluminium with those three recesses cut into it at fixed positions. There is no wrapper, no list of contents, no bookkeeping: the sensor tray is the region of the block 40 millimetres in, and the machinist who cut it knew that offset before the block existed. Handing somebody the housing hands them one object, and the compartments come along because they are part of it.
A Go struct is that block. The fields sit contiguously in memory at offsets the compiler works out at build time, so reading c.Name is a fixed addition to an address rather than a lookup. There is no per-object header and no field name stored anywhere at run time. This is why a struct with four small fields costs almost exactly the sum of those fields, and why the field-ordering advice from the variables lesson matters: the machinist has to respect alignment, and a badly ordered block wastes metal on padding.
Copy a housing and you have machined a second, identical one. Everything about Go struct behavior follows from that: b := a copies every field, passing a struct to a function copies it into the parameter, and a method that wants to change the original needs a pointer to it. This is the opposite of maps from the previous lesson, where the value was a handle onto a table somewhere else, and it is the reason Go programmers talk about "value types" and "reference types" as if the distinction were obvious. It becomes obvious once you have been bitten once.
Embedding is bolting a standard mount plate into the housing. The plate has its own screw holes, and once it is bolted in, those holes are reachable from the outside of the housing as though the housing had always had them. That is Go's field and method promotion: embed Envelope in Transfer and t.Seq just works. But the housing is not a kind of mount plate. A machine that accepts mount plates will not accept the housing, and no amount of embedding changes that. Go has composition and it does not have inheritance, and this analogy is the shortest way to remember which is which.
Syntax or Core Structure
Declaration, the zero value, a named-field literal, promotion through an embedded type, and the copy.
package main
import "fmt"
type Address struct {
City string
Country string
}
type Customer struct {
ID int
Name string
Address // embedded: the field is named Address, and its fields are promoted
tags []string // lowercase: visible only inside this package
}
type Point struct{ X, Y int }
func main() {
// The zero value is fully usable: every field is its own zero.
var zero Customer
fmt.Printf("zero: %+v\n", zero)
// Named fields, in any order. This is the form to use everywhere.
c := Customer{
ID: 7,
Name: "Ada",
Address: Address{City: "London", Country: "gb"},
tags: []string{"beta"},
}
// Promotion: c.City and c.Address.City are the same storage.
fmt.Println("city:", c.City, "same:", c.City == c.Address.City)
// Assignment copies every field, including the embedded struct.
copyOf := c
copyOf.Name = "Grace"
copyOf.City = "Bristol"
fmt.Printf("original: %s/%s\n", c.Name, c.City)
fmt.Printf("copy: %s/%s\n", copyOf.Name, copyOf.City)
// Structs whose fields are all comparable support == directly.
fmt.Println("equal:", Point{1, 2} == Point{1, 2})
// c == copyOf would NOT compile: Customer has a []string field.
}
Output:
zero: {ID:0 Name: Address:{City: Country:} tags:[]}
city: London same: true
original: Ada/London
copy: Grace/Bristol
equal: true
Four things are worth pausing on. The zero value printed something sensible without any constructor running. The embedded field is named after its type, which is why %+v shows Address:{...} and why you can still write c.Address when you want the whole thing. copyOf.City = "Bristol" changed the copy's embedded Address, not the original's, because the embedded struct is stored inline rather than pointed at. And equality is a property the compiler derives from the fields: add one slice, map or function field and == stops compiling on that type.
Technical Depth: Literals, Layout, Embedding and Defined Types
The five ways to make one
| Form | Example | When |
|---|---|---|
| Named-field literal | Customer{ID: 7, Name: "Ada"} | Almost always. Omitted fields are zero. |
| Positional literal | Point{1, 2} | Only for tiny types you own, where field order is part of the design. |
| Zero value | var c Customer | When the zero value is meaningful, which is a design goal. |
| Pointer literal | &Customer{ID: 7} | When callers need to share and mutate one instance. |
new | new(Customer) | Rare. &Customer{} says the same thing and lets you set fields. |
A positional literal breaks silently in the worst case: add a field of the same type in the middle and every positional literal still compiles while meaning something new. go vet's composites check flags positional literals for structs imported from other packages, but it cannot help you inside your own.
Visibility is per field, not per struct
Capitalisation controls export at the field level. A struct can be exported while half its fields are not, which is the normal way to publish a type whose internals you intend to change. Unexported fields are invisible to other packages, and that includes encoding/json, reflect-based mappers and fmt's %+v when called from outside — the reflection lesson in module 9 shows why. If a field must be settable from anywhere, export it; if it must not, keep it lowercase and provide a method.
Size, alignment and padding
Fields are laid out in declaration order with padding inserted so each field lands on its natural alignment boundary. On a 64 bit platform struct{ a bool; b int64; c bool } occupies 24 bytes and struct{ b int64; a, c bool } occupies 16, for exactly the same data. Order fields widest-first when a type is allocated in bulk; ignore it entirely for the handful of config structs your program creates once. Never assume a specific size in code — use unsafe.Sizeof if you need to inspect it, and treat the answer as platform-specific.
Comparability
| Field types present | == works | Usable as a map key |
|---|---|---|
| Numbers, strings, bools, pointers, channels | Yes | Yes |
| Arrays of comparable types | Yes | Yes |
| Nested comparable structs | Yes | Yes |
| Interfaces | Compiles; panics at run time if the dynamic types are not comparable | Same risk |
| Slices, maps, functions | No, compile error | No |
Comparison is field by field in declaration order, and it stops at the first difference. Two structs of the same type with equal fields are equal even if they live at different addresses; padding bytes are not compared.
Embedding, precisely
Write a type name with no field name and you get a field whose name is the unqualified type name: Address for Address, and Mutex for sync.Mutex. Its exported and unexported fields and methods are promoted — reachable as if they were declared on the outer struct — one level at a time, and promotion is transitive through further embedding.
| Rule | Consequence |
|---|---|
| Shallowest name wins | A field declared on the outer struct shadows a promoted one of the same name. |
| Equal depth is ambiguous | Two embedded types with the same field name: the selector is a compile error, but only if you actually write it. Qualify it (x.A.Name) to resolve. |
| Promotion is not conversion | A Transfer that embeds Envelope cannot be passed where an Envelope is wanted. Pass t.Envelope. |
| Method sets are inherited, dispatch is not | The outer type gains the inner type's methods verbatim. There is no override and no virtual call: an inner method calling another method calls the inner one. |
| You can embed a pointer | *Logger promotes the same names and starts out nil, so a promoted call on the zero value panics. |
| You can embed an interface | The outer struct satisfies that interface by forwarding, which is the standard trick for wrapping one implementation and replacing a method or two. |
The fourth rule is the one that surprises people arriving from Java or C#. Embedding is delegation with syntactic sugar, not subclassing. Module 12 builds the composition patterns that Go uses instead.
Anonymous structs
A struct type can be written inline, with no name:
tests := []struct {
name string
in int
want string
}{
{"zero", 0, "none"},
{"one", 1, "single"},
}
This is the standard table-test shape, and it is also handy for shaping a one-off JSON response without polluting the package with a type nobody else needs. Two anonymous struct types are identical, and therefore assignable to each other, when their fields, types and tags all match in order.
The empty struct
struct{} occupies zero bytes. map[string]struct{} is the idiomatic set because the values cost nothing, and chan struct{} is the idiomatic "something happened" signal because there is no data to misread. The literal is struct{}{} — the type followed by an empty value — which looks like a typo the first ten times you write it.
Struct tags
A tag is a string literal after the field type, conventionally a raw string, holding space-separated key:"value" pairs:
type Customer struct {
ID int `json:"id"`
Name string `json:"name"`
Note string `json:"note,omitempty"`
Key string `json:"-"`
}
Tags are inert metadata. The compiler stores them and checks nothing about their contents, so json:"nmae" is a silent bug that only shows up as a missing field at run time. go vet's structtag check catches malformed syntax and duplicate keys, which is most of what goes wrong. Module 9 covers reading them with reflect, and module 10 covers what encoding/json does with them.
Defined types versus aliases
type Cents int64 // a new, distinct type
type Money = int64 // an alias: another spelling of int64
Defined type (type Cents int64) | Alias (type Money = int64) | |
|---|---|---|
| Identity | A distinct type | The same type, different name |
| Mixing with the underlying type | Requires explicit conversion | Free, they are identical |
| Can have methods | Yes, in the package that defines it | No, it is not a new type |
| Shows in error messages as | Cents | int64 |
| Typical use | Domain modelling, units, preventing mix-ups | Migrating a type between packages without breaking callers |
The conversion rule has one deliberate hole: untyped constants convert implicitly, so var c Cents = 2500 and c += 25 both compile. A typed int64 variable does not, and that asymmetry is exactly what you want — literals stay readable while variables of the wrong unit are rejected. Any defined type can carry methods, which is why type Cents int64 is worth declaring even for a single String method; module 5 covers that in full.
Constructors and zero-value design
Go has no constructors. The convention is a package-level function named New or NewThing returning the type or a pointer to it, used when construction has invariants to enforce or expensive setup to do. It is not required, and the better goal is a type whose zero value already works: sync.Mutex, bytes.Buffer and strings.Builder all need nothing but var b bytes.Buffer. Reach for New when the zero value would be a trap, and skip it when it would not.
Real World Example: A Ledger of Two Event Types
Two event kinds share an envelope by embedding it, amounts are a defined type with its own formatting, and the balances come out sorted.
package main
import (
"fmt"
"sort"
)
type AccountID string
type Cents int64
// A method on a defined type: every amount now formats one way.
func (c Cents) String() string {
sign := ""
if c < 0 {
sign, c = "-", -c
}
return fmt.Sprintf("%s%d.%02d", sign, int64(c)/100, int64(c)%100)
}
type Envelope struct {
Seq int
Source string
}
type Transfer struct {
Envelope
From AccountID
To AccountID
Amount Cents
}
type Adjustment struct {
Envelope
Account AccountID
Delta Cents
Reason string
}
// Takes the envelope explicitly: there is no implicit upcast in Go.
func line(e Envelope, kind, detail string) string {
return fmt.Sprintf("seq %d %-3s %-8s %s", e.Seq, e.Source, kind, detail)
}
func main() {
// Positional literals, tolerable in fixed test data and nowhere else.
transfers := []Transfer{
{Envelope{1, "web"}, "acc-a", "acc-b", 2500},
{Envelope{3, "web"}, "acc-b", "acc-c", 1000},
}
adjustments := []Adjustment{
{Envelope{2, "ops"}, "acc-a", -250, "chargeback"},
{Envelope{4, "ops"}, "acc-c", 75, "goodwill"},
}
balances := map[AccountID]Cents{"acc-a": 10000, "acc-b": 0, "acc-c": 500}
for _, t := range transfers {
balances[t.From] -= t.Amount
balances[t.To] += t.Amount
detail := fmt.Sprintf("%s -> %s %s", t.From, t.To, t.Amount)
fmt.Println(line(t.Envelope, "transfer", detail))
}
for _, a := range adjustments {
balances[a.Account] += a.Delta
detail := fmt.Sprintf("%s %s (%s)", a.Account, a.Delta, a.Reason)
fmt.Println(line(a.Envelope, "adjust", detail))
}
ids := make([]AccountID, 0, len(balances))
for id := range balances {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
fmt.Println("--")
var total Cents
for _, id := range ids {
fmt.Printf("%-6s %8s\n", id, balances[id])
total += balances[id]
}
fmt.Printf("%-6s %8s\n", "total", total)
// Every field is comparable, so == and map keys both work.
fmt.Println("first two transfers identical:", transfers[0] == transfers[1])
}
Output:
seq 1 web transfer acc-a -> acc-b 25.00
seq 3 web transfer acc-b -> acc-c 10.00
seq 2 ops adjust acc-a -2.50 (chargeback)
seq 4 ops adjust acc-c 0.75 (goodwill)
--
acc-a 72.50
acc-b 15.00
acc-c 15.75
total 103.25
first two transfers identical: false
The embedding earns its keep in line(t.Envelope, ...) — and in what that call is not allowed to be. t.Seq and t.Source read as though Transfer declared them, so every event type gets sequencing and provenance without repeating two fields, and adding a TraceID to Envelope adds it to both types at once. But line(t, ...) does not compile. Go will not treat a Transfer as an Envelope no matter how it is embedded, so you name the field. When you genuinely need one function that accepts either event, the answer is an interface, and that is module 5's subject.
type Cents int64 is doing two jobs. The String method means no caller can accidentally print a raw 10325 where an amount belongs: %s and %v both route through it, and the padding in %8s applies to the formatted result. Meanwhile the type keeps money out of the wrong slots — balances[id] += someCount is a compile error when someCount is an int — while untyped constants like 2500 and 75 stay perfectly readable in the literals. That combination, a distinct type plus one formatting method, is most of what "domain modelling in Go" amounts to.
The test fixtures use positional literals, which is the one context where they are defensible: the data is a handful of lines, it sits next to the type, and a mismatch fails immediately. Production code should not look like this. Insert a Currency field between To and Amount and {Envelope{1, "web"}, "acc-a", "acc-b", 2500} stops compiling here — which is fine — but the equivalent literal with all-string fields would have compiled and silently shifted every value by one. Named fields cost eight characters and remove that failure mode entirely.
Both event structs are comparable, because Envelope, AccountID and Cents all are, so transfers[0] == transfers[1] works and either type could be used as a map key or deduplicated with a map[Transfer]struct{}. Add a []string of labels to Envelope and every one of those uses stops compiling, in both types at once, which is a good reason to keep collection fields out of small embedded value types. The key-sorting ritual is the same one from the maps lesson; with Go 1.21 or later, slices.Sorted(maps.Keys(balances)) replaces the loop and the sort.Slice call outright, and it works for AccountID because its underlying type is a string.
Common Mistakes
- Expecting embedding to be inheritance. A
Transferis not anEnvelope, cannot be assigned to one, and cannot be passed to a function expecting one. There is also no overriding: if an embedded method calls another method on itself, it calls the embedded type's version, never the outer type's replacement. Use interfaces for polymorphism and embedding purely for reuse.
- Mutating a copy and wondering why nothing happened.
for _, c := range customers { c.Name = "x" }changes a copy each iteration. So does passing a struct to a function by value. Usecustomers[i].Name = "x"or a pointer.
- Positional literals in long-lived code. They compile today and mean something different after a field is added or reordered. Name every field except in the tiniest types you fully own.
- Assuming
%+vshows everything. Unexported fields are printed byfmtbut are invisible toencoding/jsonand to any other package's reflection, so a struct that looks complete in a log can serialise to{}.
- Typos in struct tags.
json:"nmae"compiles, vets clean if the syntax is valid, and produces a field nobody can find. Round-trip one value through your encoder in a test rather than trusting the tag by eye.
- Copying a struct that contains a lock.
sync.Mutexembedded in a struct means the struct must never be copied after first use; the copy gets a second, independent lock and the mutual exclusion silently disappears.go vet'scopylockscheck catches the obvious cases. Keep such types behind pointers.
- Embedding a pointer and forgetting it starts nil.
struct{ *Logger }promotesLogger's methods onto the zero value, where calling one panics. Embed the value, or make the constructor mandatory.
- Comparing structs that contain interfaces.
==compiles, then panics at run time withcomparing uncomparable typeif the dynamic value turns out to be a slice or map. If a field is anany, compare explicitly instead.
- Declaring an alias when you meant a defined type.
type Cents = int64gives you no type safety and cannot carry methods. The=is easy to add by muscle memory and hard to spot in review.
- Reordering fields for looks in a hot type. Alphabetising the fields of a struct you allocate by the million can add padding and cost real memory. Measure before caring, and leave a comment when the order is deliberate.
- Reaching for
Newreflexively. A constructor that only assigns the arguments to fields is a literal with extra steps, and it blocks callers from using named fields. Write one when there is an invariant to enforce.
Best Practices
- Design the zero value to be useful. If
var x Tis safe to use, callers need no constructor, embedding works cleanly, andTcomposes into other structs without ceremony.
- Use named fields in every composite literal outside of small self-owned types and adjacent test tables.
- Keep structs small enough to pass by value, or always pass them by pointer. Pick one per type and be consistent; mixed receivers and mixed parameter styles on the same type are where the copy bugs live.
- Group fields by lifetime and meaning first, then by width. Readability wins for the ninety-nine percent of types that are not allocated in a hot loop.
- Embed for reuse, interface for substitution. If you find yourself wanting to override a promoted method, you want an interface field instead.
- Export the minimum. Start every field lowercase and promote it only when a caller outside the package genuinely needs it.
- Give units and identifiers their own defined types.
Cents,AccountID,UserIDandSecondscost one line each and remove a whole category of argument-order bug.
- Verify tags with a round-trip test. Encode a fully populated value, decode it back, compare. It catches typos, missing exports and
omitemptysurprises in one assertion.
Practice Exercises
- Define
type Duration int64with aStringmethod that renders it asNm Ns(for example3m 07s), then write a structJob{ID string; Elapsed Duration}and print a slice of jobs in a fixed-width table. Confirm that assigning a plainint64variable toElapsedfails to compile, while assigning the literal90succeeds.
- Build
Base{ID int; Kind string}and two types that embed it,TaskandNote. Write a function that takes aBaseand prints it, call it from both, and then add a field namedKinddirectly toTask. Predict whattask.Kindrefers to before you compile, and confirm how you would reach the shadowed one.
- Write a struct with a
bool, anint64and anotherboolin that order, printunsafe.Sizeoffor it, then reorder the fields widest-first and print it again. Explain the difference in a comment, noting that the numbers are specific to your platform.
- Take the ledger example and make
Envelopecarry aLabels []stringfield. Fix every compile error that results, then decide whether to keep the field onEnvelope, move it to the two outer structs, or replace it with a comparable alternative — and write down which you chose and why.