Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 147 ยท Structs and Methods

Structs

Learn Go structs - declaring types, named-field literals, zero values, nested and anonymous structs, comparing and copying, struct tags, and exported versus unexported fields.

A struct groups several values, called fields, into one new type. Where an int holds a single number and a slice holds a list of one kind of thing, a struct can hold a name, an age, an email address and a list of tags all at once, each with its own type.

Structs are the backbone of Go programs. Go has no classes: you model your data with structs, attach behavior with methods, and describe shared behavior with interfaces. This lesson covers declaring structs, creating them, zero values, nesting, anonymous structs, comparison and copying, a first look at struct tags, and how capitalization controls what other packages can see.

Declaring a struct type

A struct type lists its fields, each with a name and a type, inside braces. You normally give it a name with a type declaration (see defined types).

Go Declaring and using a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Fields are read and written with a dot: p.Name. Fields of the same type can share a declaration (X, Y int), and the verb %+v prints field names, which is very helpful while debugging. Use %#v to see the Go-syntax form with the type name.

Struct literals

A composite literal creates a struct and sets its fields in one expression. There are two forms.

  • Named fields (preferred): Person{Name: "Ada", Age: 36}. Order does not matter and omitted fields get their zero values.
  • Positional: Person{"Ada", 36, "London"}. You must supply every field in declaration order.
Go Named and positional literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Positional literals are fragile: adding a field to Person later breaks every one of them. Use named fields except for tiny, stable types like Point{1, 2}.

You can also build a struct and then take its address with &, or ask for a pointer directly. Both yield a *Person:

Go Pointers to structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Zero values: make them useful

If you declare a struct without initializing it, all fields take their zero values: 0, "", false, nil. A struct whose fields are all zero-valued is the zero value of the struct, and good Go types are designed so that this state is meaningful and safe.

Go The zero value of a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

SafeLog needs no constructor because each field's zero value is ready to use. A struct that holds a map or a channel typically needs a constructor, because those zero values are nil (see new, make and composite literals).

Why structs, and where they fall short

Structs are Go's way of modelling a "thing". Their strengths: related data travels as one value; fields are typed, so the compiler catches mistakes; the memory layout is compact and predictable (memory layout); and a struct that contains only comparable fields can be a map key. Their limits: a struct has no inheritance (reuse comes from embedding), no constructors or default field values beyond the zero value, no way to make a field read-only except by unexporting it, and large structs are copied on every assignment and call unless you use a pointer.

Fields can also be declared without a name, only a type. Such an anonymous (embedded) field takes the type's name and promotes its fields and methods to the outer struct, so Employee{Person: Person{...}} can be read as e.Name directly. The embedding lesson covers promotion and its rules in full.

Nested structs

A field can itself have a struct type. Dots chain to reach inner fields.

Go Nested structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

A struct cannot contain itself by value (it would have infinite size), but it can contain a pointer to its own type, which is how linked lists and trees are built. When you want the inner fields promoted to the outer struct, use embedding instead of a named field.

Anonymous structs

You can use a struct type without naming it. This is common for one-off groupings: table-driven tests, small configuration values and JSON snippets.

Go Anonymous structs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The slice of anonymous structs above is the idiomatic shape of a table-driven test. Two anonymous struct types with identical fields (names, types, order and tags) are the same type, so values can be assigned between them.

Comparing structs

Structs are compared with == if all their fields are comparable. Two struct values are equal when every corresponding field is equal. That also lets you use such structs as map keys.

Go Comparing structs and using them as map keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If a struct contains a slice, map or function, it is not comparable, and the compiler refuses:

Go Incomparable fields (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler reports invalid operation: a == b (struct containing []int cannot be compared). To compare such values, write your own comparison, or use reflect.DeepEqual in tests, or slices.Equal on the slice field.

Copying structs

Assigning a struct, or passing it to a function, copies all fields. The copy is independent, with one big caveat: pointers, slices and maps inside the struct are copied as references, so the copy and the original share what they point to. This is called a shallow copy.

Go Struct assignment is a shallow copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

For a real deep copy, copy the slices and maps explicitly (slices.Clone, maps.Clone) and allocate new pointees.

Struct tags

A field can carry a tag, a raw string literal after its type. The compiler ignores it, but libraries read tags through reflection. The encoding/json package, for example, uses them to choose JSON names:

Go
type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email,omitempty"`
	pass  string // unexported: invisible to other packages, including json
}

Tag conventions, omitempty, and reading tags yourself are covered in Struct Tags and the JSON lesson.

Exported and unexported fields

Capitalization is Go's access control. A field whose name starts with an upper-case letter is exported and visible to other packages; a lower-case field is unexported and visible only inside its own package. The same rule applies to types, functions and methods.

Go Exported fields and reflection-based packages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Everything in the main package is in one package, so the code above could read a.pin directly. The point is that encoding/json, a different package, ignores pin. Keep fields unexported when you want to protect invariants, and offer methods to work with them.

Field order affects memory size, because the compiler inserts padding for alignment. For most structs this does not matter, but see Struct Memory Layout and Alignment if you store millions of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Printf("%+v", Person{Name: "Ada"}) print for type Person struct { Name string; Age int }?

    The + flag adds field names. %v would print {Ada 0}, and %#v would print the Go-syntax form shown in option 3.
  2. 2. Why are named-field literals preferred over positional ones?

    Positional literals must list every field in order, so adding a field breaks them. Named fields are robust and self-documenting.
  3. 3. Which struct type can be compared with ==?

    A struct is comparable only if all fields are. Slices, maps and funcs are not comparable.
  4. 4. After b := a where a.Items is a slice, does b.Items[0] = 9 change a.Items[0]?

    Struct assignment copies fields shallowly. The slice header is copied, but it still points at the same array.
  5. 5. What decides whether a struct field is visible to other packages?

    Names that start with an upper-case letter are exported. Lower-case names are visible only within their own package.

Summary

  • A struct groups named, typed fields into one type; access fields with a dot, which also works through pointers.
  • Prefer named-field literals (Person{Name: "Ada"}); omitted fields get their zero values.
  • Design structs so that the zero value is useful; use constructors when it is not.
  • Structs can nest, hold pointers to their own type, and be anonymous (great for tables of test cases).
  • == works when every field is comparable; such structs can be map keys.
  • Assignment copies the struct shallowly: pointers, slices and maps still share their targets.
  • Tags are metadata for libraries; upper-case field names are exported, lower-case ones are private to the package.

Next: Methods