Thuta Learning
Go
IntermediateProgrammingBeginner

Structs

GoLesson 1230 min

What you'll walk away with

  • Declare a struct type with type Name struct { ... } and create values with keyed literals
  • Predict output knowing that assigning a struct copies it while a pointer edits the original
  • Explain when structs can be compared with == and when that is a compile error
  • Use embedding and promoted fields, and apply the uppercase/lowercase export rule

Explain it simply

Explain it simply

Think of a struct as a form template. A membership form has boxes for name, email and age, and each box says what kind of value goes in it. type User struct is the template, and User{Name: "Aung", ...} is one filled-in copy of the form.

Instead of juggling three separate variables for name, email and age, you pass one User to functions, keep it in a slice, or turn it into JSON. Go has no classes; structs, together with the methods in the next lesson, fill that role.

Problem → Why → Solution

The problem: swapped fields that nobody notices

A struct literal can list its values by position, without field names: User{"Aung", "aung@example.com", 25}. But Name and Email are both strings, so if you swap them the compiler says nothing. The mailing system tries to send email to "Aung", and the bug only surfaces in production.

main.go
package main

import "fmt"

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	u := User{"aung@example.com", "Aung", 25} // compiles: both are strings
	fmt.Println("sending mail to", u.Email)    // sending mail to Aung
}

Why are keyed literals safer?

A positional literal depends on field order, so it cannot catch two same-typed fields being swapped. Worse, adding a new field to the struct turns every positional literal into a "too few values in struct literal" error. A keyed literal such as User{Name: "Aung", Email: "aung@example.com"} does not depend on order and gives omitted fields their zero value, which protects against both problems.

Core concept: a value type made of fields

type User struct { Name string; Email string; Age int } declares a new type called User. You read and write individual fields with a dot, as in user.Name. A plain var guest User sets every field to its zero value: Name is "" and Age is 0. fmt.Printf("%+v", guest) prints the field names too, which is handy when debugging. When a struct needs setup before it is usable, such as a map field that must be made, Go code conventionally provides a constructor function named NewUser that returns a ready value.

Like an array, a struct is a value type. copyUser := user copies every field, so changing copyUser.Age leaves user alone, and passing a struct to a function also hands over a copy. To edit the original, use a pointer: after p := &user, p.Age++ is automatically treated as (*p).Age++, so user.Age itself changes.

If every field is comparable, two structs can be compared field by field with ==, and the struct can be a map key. A single slice, map or function field makes == a compile error, "struct containing []string cannot be compared", and you compare such structs yourself with functions like slices.Equal.

A field whose name starts with an uppercase letter is exported and visible from other packages; a lowercase one is visible only inside its own package, and encoding/json encodes only exported fields. Placing one struct inside another without a field name is called embedding, and the inner fields are promoted, so you can write customer.City. This is composition, not inheritance: a Customer simply contains an Address.

Mental model: hand over a photocopy, or the address
  1. The type lists the fields
  2. Create with a literal or zero value
  3. = and calls copy every field
  4. Pass &value to edit the original

Handing over a struct hands over a photocopy; to let someone edit the real form, give them its address, a pointer.

General pattern

go
type TypeName struct {
	ExportedField   FieldType
	unexportedField FieldType
	EmbeddedType              // fields are promoted
}

value := TypeName{ExportedField: x}   // omitted fields get zero values
var empty TypeName                    // every field is a zero value
value.ExportedField = y
ptr := &value
ptr.ExportedField = z                 // same as (*ptr).ExportedField

Always prefer keyed literals. Uppercase fields are exported from the package, the fields of an embedded type can be used directly, and a pointer lets you read and write fields with a plain dot.

Example: a User struct with copies, a pointer and ==

This program creates a User with a keyed literal, reads its fields, prints a zero-value User with %+v, edits a copy, edits the original through a pointer, and finally compares with ==. Think about why the "25 30" and "26 true" lines come out the way they do.

main.go
package main

import "fmt"

type User struct {
	Name  string
	Email string
	Age   int
}

func main() {
	user := User{Name: "Aung", Email: "aung@example.com", Age: 25}
	fmt.Println(user.Name)
	fmt.Println(user.Email)

	var guest User
	fmt.Printf("%+v\n", guest)

	copyUser := user
	copyUser.Age = 30
	fmt.Println(user.Age, copyUser.Age)

	p := &user
	p.Age++
	fmt.Println(user.Age, user == User{Name: "Aung", Email: "aung@example.com", Age: 26})
}

Code breakdown

  1. Type declarationtype User struct {

    A new type with three fields: Name, Email and Age. All three start with uppercase letters, so they are exported.

  2. Keyed literaluser := User{Name: "Aung", Email: "aung@example.com", Age: 25}

    Values are matched to field names, so order cannot go wrong. user.Name and user.Email then print Aung and aung@example.com.

  3. Zero valuefmt.Printf("%+v\n", guest)

    guest was only declared, so its strings are empty and Age is 0, printed as {Name: Email: Age:0}.

  4. CopycopyUser := user

    Every field is copied, so copyUser.Age = 30 changes only the copy and the line prints "25 30".

  5. Pointerp := &user

    p holds user's address. p.Age++ means (*p).Age++, so user.Age itself becomes 26.

  6. Comparisonuser == User{Name: "Aung", Email: "aung@example.com", Age: 26}

    All three fields are strings or ints, so User is comparable. Every field matches, giving true.

You should see
Aung
aung@example.com
{Name: Email: Age:0}
25 30
26 true

Embedding, struct tags and anonymous structs

Customer embeds Address without a field name, so you can read c.City directly or spell it out as c.Address.City. A struct tag in backticks, such as json:"name", tells encoding/json which JSON key to use. The lowercase note field is unexported, so it is left out of the JSON. The last lines create an anonymous struct, which is convenient for one-off data.

embed.go
package main

import (
	"encoding/json"
	"fmt"
)

type Address struct {
	City string `json:"city"`
}

type Customer struct {
	Name    string `json:"name"`
	Address        // embedded: City is promoted
	Points  int    `json:"points"`
	note    string // unexported: json skips it
}

func main() {
	c := Customer{Name: "Su", Address: Address{City: "Yangon"}, Points: 120, note: "vip"}
	fmt.Println(c.Name, c.City, c.Address.City, c.Points, c.note) // Su Yangon Yangon 120 vip

	data, _ := json.Marshal(c)
	fmt.Println(string(data)) // {"name":"Su","city":"Yangon","points":120}

	point := struct{ X, Y int }{3, 4}
	fmt.Printf("%+v\n", point) // {X:3 Y:4}
}

In real projects

Where this shows up in real projects

In a Go web service, structs describe every shape of data: a CreateUserRequest for decoding the HTTP request body, a User for a database row, a UserResponse for the API reply. Tags such as json:"email" connect the Go field Email to the JSON key email, and a lowercase field is left out of the JSON entirely. Teams often use a separate response struct so sensitive data such as a password hash can never leak into a response.

Embedding saves repeating common fields; for example, a Model struct holding ID, CreatedAt and UpdatedAt can be embedded in Product and Order. When large structs live in a slice and must be edited in a loop, it is easy to edit a copy by mistake, so edit users[i] by index or keep a pointer slice ([]*User). Comparable structs also make good map keys, as in map[Point]bool for grids and coordinates.

Common mistakes

Common mistakes

1. Expecting lowercase fields to be exported

With type User struct { name string }, reading u.name from another package is a compile error, and json.Marshal(u) quietly produces {}. Data disappearing without any error is the dangerous part. Start fields that must be visible outside the package with an uppercase letter, and use a tag when you want a lowercase JSON key.

2. Editing a struct parameter and expecting the caller to see it

func birthday(u User) { u.Age++ } increments the copy's Age, so the caller's user.Age is unchanged. Accept a pointer instead, func birthday(u *User) { u.Age++ }, and call birthday(&user).

3. Comparing structs that contain a slice with ==

Once a Team struct has a Members []string field, a == b fails to compile with "struct containing []string cannot be compared", and the type can no longer be a map key. Write a function that compares Name with == and Members with slices.Equal.

Best practices

Best practices

  • Always write field names in struct literals, so adding a field later does not break existing code.
  • Design the zero value to be useful: if var cfg Config works immediately, nobody needs a constructor.
  • Store money as an integer such as PriceCents int rather than float64 to avoid rounding errors.
  • Pass large structs that need editing by pointer, and pass small value-like structs by copy.

Mini challenge

Mini challenge: products and order lines

Write a Product struct and a LineItem struct that embeds it, and show the difference between a copy and a pointer in the output. Methods come in the next lesson, so use plain functions here.

  • Product has Name string and PriceCents int (store money as integer cents)
  • LineItem embeds Product and adds Qty int; use promoted fields such as item.Name
  • Write lineTotal(item LineItem) int and discount(p *Product, percent int)
  • After discounting tea, print that the copy inside item is unchanged, plus an == result
shop.go
package main

import "fmt"

type Product struct {
	// TODO: Name string, PriceCents int
}

type LineItem struct {
	// TODO: embed Product, add Qty int
}

func lineTotal(item LineItem) int {
	// TODO: price times quantity, using the promoted field
	return 0
}

func discount(p *Product, percent int) {
	// TODO: lower p.PriceCents by percent
}

func main() {
	// TODO: tea costs 250 cents; build a LineItem with Qty 4
	// TODO: print name and total, discount tea by 20,
	// print tea's price and the item's price, then compare with ==
	fmt.Println("todo")
}

Expected: Tea 1000 200 250 true

Show hint

LineItem{Product: tea, Qty: 4} copies tea into the item. So after discount(&tea, 20), tea.PriceCents is 200 while item.PriceCents stays 250.

Show solution
shop.go
package main

import "fmt"

type Product struct {
	Name       string
	PriceCents int
}

type LineItem struct {
	Product
	Qty int
}

func lineTotal(item LineItem) int {
	return item.PriceCents * item.Qty
}

func discount(p *Product, percent int) {
	p.PriceCents -= p.PriceCents * percent / 100
}

func main() {
	tea := Product{Name: "Tea", PriceCents: 250}
	item := LineItem{Product: tea, Qty: 4}
	fmt.Println(item.Name, lineTotal(item))

	discount(&tea, 20)
	fmt.Println(tea.PriceCents, item.PriceCents)
	fmt.Println(tea == Product{Name: "Tea", PriceCents: 200})
}

Quick quiz 1 / 3

What does a := User{Name: "Su"}; b := a; b.Name = "Mya"; fmt.Println(a.Name) print?

Quick quiz 2 / 3

Which struct type cannot be used as a map key?

Quick quiz 3 / 3

In type Customer struct { Address; Name string }, where Address has a City field, which expression is valid?

What to remember

  • type Name struct { ... } groups fields into one type, and keyed literals are the safest way to build values.
  • Structs are values: assigning or passing one copies it, and only a pointer (&value) lets you edit the original.
  • Only structs whose fields are all comparable work with == and as map keys; one slice field rules both out.
  • Only uppercase fields are exported and encoded to JSON, and embedding is composition that promotes fields.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Structs | Thuta Learning