TExcelTAD
Home › Go › Go Structs

Go Structs

A struct groups several named values — called fields — into one unit. Where a slice holds many values of the same type, a struct holds a fixed set of values of different types that belong together: a user's name, email and age; a product's title, price and stock. Go has no classes; structs (plus methods, covered later) fill that role.

Defining a struct type

go · try it yourself
package main

import "fmt"

type Book struct {
	Title  string
	Author string
	Pages  int
	OnLoan bool
}

func main() {
	var b Book // all fields get their zero values
	fmt.Printf("%+v\n", b)

	b.Title = "The Go Programming Language"
	b.Author = "Donovan & Kernighan"
	b.Pages = 380
	fmt.Println(b.Title, "-", b.Pages, "pages")
}
{Title: Author: Pages:0 OnLoan:false}
The Go Programming Language - 380 pages

Fields are accessed with a dot: b.Title. Like other names, fields starting with an upper-case letter are exported (visible to other packages).

Struct literals

There are two ways to fill in a struct when you create it:

Form Example Notes
With field names Book{Title: "Dune", Pages: 412} Recommended. Order is free; missing fields are zero.
Positional Book{"Dune", "Herbert", 412, false} Must list every field in order. Fragile when fields are added.
go · try it yourself
package main

import "fmt"

type Point struct {
	X, Y int
}

type Product struct {
	Name  string
	Price float64
	Tags  []string
}

func main() {
	p1 := Point{X: 3, Y: 7}
	p2 := Point{1, 2}
	p3 := Point{Y: 5} // X is 0

	coffee := Product{
		Name:  "Coffee beans",
		Price: 12.9,
		Tags:  []string{"organic", "fair-trade"},
	}

	fmt.Println(p1, p2, p3)
	fmt.Printf("%+v\n", coffee)
	fmt.Println(p1 == Point{3, 7}) // structs are comparable if all fields are
}
{3 7} {1 2} {0 5}
{Name:Coffee beans Price:12.9 Tags:[organic fair-trade]}
true

Structs are values

Assigning a struct, or passing it to a function, copies all its fields. To let a function modify the original, pass a pointer (*Book). Go automatically dereferences pointers when you access fields, so p.Pages works for both a Book and a *Book.

go · try it yourself
package main

import "fmt"

type Account struct {
	Owner   string
	Balance int
}

func depositCopy(a Account, amount int) {
	a.Balance += amount // modifies the copy only
}

func deposit(a *Account, amount int) {
	a.Balance += amount // modifies the original
}

func main() {
	acc := Account{Owner: "Noor", Balance: 100}

	depositCopy(acc, 50)
	fmt.Println(acc.Balance)

	deposit(&acc, 50)
	fmt.Println(acc.Balance)

	backup := acc
	backup.Balance = 0
	fmt.Println(acc.Balance, backup.Balance)
}
100
150
150 0

Nested and embedded structs

A struct field can itself be a struct. With embedding — writing just a type name without a field name — the inner fields are promoted, so you can access them directly.

go · try it yourself
package main

import "fmt"

type Address struct {
	Street string
	City   string
}

type Contact struct {
	Email string
	Phone string
}

type Customer struct {
	Name    string
	Address Address // named field
	Contact         // embedded field
}

func main() {
	c := Customer{
		Name:    "Ravi",
		Address: Address{Street: "12 Hill Rd", City: "Pune"},
		Contact: Contact{Email: "ravi@example.com"},
	}

	fmt.Println(c.Address.City) // through the named field
	fmt.Println(c.Email)        // promoted from Contact
	fmt.Println(c.Contact.Email)
}
Pune
ravi@example.com
ravi@example.com

Anonymous structs and slices of structs

For one-off data — test cases, a quick table — you can declare a struct type inline without naming it. Slices of structs are the most common way to hold records.

go · try it yourself
package main

import "fmt"

func main() {
	team := []struct {
		Name  string
		Goals int
	}{
		{"Ana", 7},
		{"Ben", 3},
		{"Cleo", 11},
	}

	best := team[0]
	for _, player := range team {
		if player.Goals > best.Goals {
			best = player
		}
	}
	fmt.Printf("Top scorer: %s with %d goals\n", best.Name, best.Goals)
}
Top scorer: Cleo with 11 goals

Tip: Go has no constructors. By convention, write a function named NewThing(...) that returns a ready-to-use Thing or *Thing when creating one needs validation or defaults.

Test yourself

What does fmt.Printf("%+v", Point{1, 2}) print for type Point struct{ X, Y int }?

  1. {1 2}
  2. {X:1 Y:2}
  3. Point{X:1, Y:2}
  4. [1 2]

A function receives a struct (not a pointer) and changes a field. What happens to the caller's struct?

  1. It changes
  2. Nothing — the function worked on a copy
  3. Compile error
  4. Panic

If Customer embeds Contact, which has a field Email, how can you access it?

  1. Only c.Contact.Email
  2. Only c.Email
  3. Both c.Email and c.Contact.Email
  4. c->Email