Fundamentals

Structs and Methods

Model related data with structs, attach behaviour with methods, and compose types with embedding.

What you will learn

Real programs deal with things like users, orders, and servers, each made of several related pieces of data. A struct groups those pieces into one type, and a method attaches behaviour to it. This lesson covers declaring and creating structs, writing methods, the important choice between value and pointer receivers, constructor functions, and embedding, which is how Go reuses code without inheritance.

Defining a struct

type User struct {
    ID     int
    Name   string
    Active bool
}

type User struct { ... } creates a new type named User with three fields. Each field has a name and a type. Create a value with a literal, naming each field:

user := User{
    ID:     1,
    Name:   "Mira",
    Active: true,
}

fmt.Println(user.Name) // Mira
user.Name = "Mira K."  // fields can be changed

Use the dot to read or write a field. Always name the fields in the literal. The shorter positional form, User{1, "Mira", true}, breaks as soon as someone adds or reorders a field, and it is hard to read.

Zero values

If you leave fields out, they start at their zero values:

var u User
fmt.Println(u) // {0  false}

partial := User{Name: "Sam"}
fmt.Println(partial.ID) // 0

Good Go types are designed so that this zero state is already usable, which saves you from needing setup code everywhere.

Structs are copied

A struct is a value, just like an int. Assigning it or passing it to a function copies all its fields:

a := User{Name: "Ada"}
b := a
b.Name = "Bea"

fmt.Println(a.Name, b.Name) // Ada Bea

To share one struct instead, use a pointer: p := &a. Go lets you write p.Name instead of (*p).Name.

Adding methods

A method is a function with a receiver, written between func and the method name:

func (u User) DisplayName() string {
    if u.Name == "" {
        return "Anonymous"
    }
    return u.Name
}

func main() {
    user := User{Name: "Mira"}
    fmt.Println(user.DisplayName()) // Mira

    var empty User
    fmt.Println(empty.DisplayName()) // Anonymous
}

(u User) says "this function belongs to User, and inside it the value is called u". You call it with the dot, as user.DisplayName(). Methods can be added to any type you define in the same package, not only structs.

Value or pointer receiver?

This is the decision you will make most often with methods. A value receiver gets a copy of the struct:

func (u User) Deactivate() {
    u.Active = false // changes only the copy
}

A pointer receiver gets the original:

func (u *User) Deactivate() {
    u.Active = false // changes the real user
}

Calling it looks the same either way. With a pointer receiver, user.Deactivate() works on a normal variable because Go passes &user for you.

Use a pointer receiver whenUse a value receiver when
The method changes the structThe method only reads the struct
The struct is large and copying is wastefulThe struct is small
The struct holds something that must not be copied, like a mutexThe type behaves like a plain value, such as a coordinate

Be consistent. If any method of a type needs a pointer receiver, make all of them pointer receivers. Mixing the two makes the rules for interfaces, covered in the next lesson, harder to follow.

Constructors are plain functions

Go has no special constructor syntax. A function that returns a ready-to-use value is the convention, usually named NewTypeName:

func NewUser(id int, name string) User {
    return User{ID: id, Name: name, Active: true}
}

Constructors are worth writing when there are defaults to apply or inputs to check. For simple data, a literal is fine. Many constructors return a pointer, *User, when the type has pointer receivers.

Printing a struct

fmt.Println(user) prints the fields in braces. Use %+v to include the field names:

fmt.Printf("%v\n", user)  // {1 Mira true}
fmt.Printf("%+v\n", user) // {ID:1 Name:Mira Active:true}

To control the output yourself, give the type a String method. The fmt package calls it automatically:

func (u User) String() string {
    return fmt.Sprintf("%s (#%d)", u.Name, u.ID)
}

fmt.Println(user) // Mira (#1)

Embedding: composition, not inheritance

Go has no classes or inheritance. To reuse a type inside another, you embed it by listing its type without a field name:

type Contact struct {
    Email string
}

func (c Contact) Domain() string {
    return strings.Split(c.Email, "@")[1]
}

type Customer struct {
    Contact // embedded
    Name    string
}

func main() {
    c := Customer{
        Contact: Contact{Email: "mira@example.com"},
        Name:    "Mira",
    }

    fmt.Println(c.Email)    // promoted field
    fmt.Println(c.Domain()) // promoted method: example.com
}

The embedded type's fields and methods are promoted, so you can use them as if they belonged to Customer. Embedding is composition: a Customer has a Contact, and it is not a kind of Contact. If Customer defines its own Domain method, it takes priority.

Comparing structs

Two structs of the same type are equal with == when all their fields are equal. This only works if every field is comparable, so a struct containing a slice or map cannot be compared directly.

Exported fields

The capitalisation rule applies to fields and methods as well. Name can be read from other packages, while name cannot. Keep fields lowercase when you want callers to go through methods, so that you can enforce rules such as "balance never goes negative".

Common mistakes

  • Using a value receiver and expecting the struct to change. Switch to a pointer receiver.
  • Mixing value and pointer receivers on one type.
  • Using positional struct literals that break when fields change.
  • Thinking embedding is inheritance. There is no overriding through a type hierarchy and no super.
  • Copying a struct that contains a mutex or other state that must stay unique.

Practice

Create a BankAccount struct with Owner and Balance fields. Add a Deposit method and a Withdraw method. Withdraw should return an error if the amount is not positive or is larger than the balance. Show both a successful and a failing withdrawal.

Summary

A struct groups named fields into a new type, and Go sets any missing field to its zero value. Structs are copied on assignment, so use a pointer when you want to share one. A method is a function with a receiver, and the receiver should be a pointer if the method changes the struct or the struct is large. Go has no constructors, only ordinary functions by convention, and no inheritance, only embedding, which promotes the inner type's fields and methods.

Official reference: A Tour of Go: Methods and Effective Go: Embedding.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026