GO GO

Structs and Methods in Go: A Transit Card That Actually Keeps Its Top-Up

Dima Nov 17, 2026

Introduction

As soon as a program handles anything more interesting than single numbers, it needs to group values that belong together: a customer's name and email, a product's code and price, a card's number and balance. In Go that grouping is a struct, and the functions that work on it are methods. Both are simple to write, and both hide one rule that catches nearly every beginner: Go copies values far more often than you might expect, and a method that changes a copy changes nothing.

In this tutorial we will model the cards of a city's public transport system. We will start with a top-up method that runs, reports no error, and leaves the balance at zero. From there we will learn the difference between value and pointer receivers, return an error when a fare cannot be paid, find the same copying trap hiding in a for loop, and give the card a readable printed form.

I will assume you are working in the Go sandbox on Bytestark, with the terminal in /home/coder/learning, which holds a Go module named learning. You should be comfortable running a Go program with go run, and with variables, functions, if and for.


Background

A struct is a type made of named fields. type Card struct { ID string; Balance int } defines a new type, Card, whose values each hold an ID and a Balance. You reach a field with a dot: card.Balance.

A method is a function attached to a type. It is written like a function, with one extra parameter in parentheses before the name, called the receiver: func (c Card) Describe() string is a method named Describe on Card, and inside it c is the card it was called on. You call it with a dot, as in card.Describe().

Go passes everything by value: when you call a function or a method, each argument is copied into the parameter. For a struct, that means the whole struct is copied, field by field. Changes the function makes to its copy do not affect the original.

A pointer is a value that holds the address of another value, where it lives in memory. *Card is the type "pointer to a Card", and &card gives the address of the variable card. A function that receives a pointer can reach the original value through it, so its changes are visible to the caller.


Practical Scenario

A city's buses and trams use a contactless card. Riders top it up at a machine or online, and each trip deducts a fixed fare of 1.80 EUR. Each month, the transit authority adds a 2.00 EUR loyalty bonus to every registered card. The system tracks each card's balance in cents, and how many trips it has paid for.

The consequences of a bug are concrete and public. If a top-up does not stick, a rider who just paid 20 EUR is refused at the gate. If a fare is allowed on an empty card, the authority loses revenue. If the monthly bonus silently fails, thousands of riders are shortchanged, and the first anyone hears of it is a complaint in the newspaper.

We will build the card type step by step, checking at each stage that money moves where it should.


The Problem

Here is a first version of the card. It defines the Card struct and a TopUp method, creates a new card, tops it up with 20.00 EUR, and prints the balance.

Create a folder and a file:

mkdir transit
touch transit/main.go


Put this in transit/main.go:

package main

import "fmt"

type Card struct {
    ID      string
    Balance int // in cents
    Trips   int
}

func (c Card) TopUp(amount int) {
    c.Balance += amount
}

func main() {
    card := Card{ID: "C-1042"}
    card.TopUp(2000)
    fmt.Println("balance after top-up:", card.Balance)
    fmt.Println(card)
}


Go into the folder and run it:

cd transit
go run .


balance after top-up: 0
{C-1042 0 0}


The program compiled, ran without an error, and the balance is still 0. A rider who just paid 20 EUR would be turned away at the first tram.

Let's read it. type Card struct { ... } defines the type with three fields: ID, a string; Balance, the money in cents; and Trips, a count. card := Card{ID: "C-1042"} creates a card with that ID. The fields we did not mention get their zero values, 0 for both integers. card.TopUp(2000) calls the method with 2000 cents. fmt.Println(card) prints a struct as its field values in braces, in the order they were declared, which is the {C-1042 0 0} on the last line.

The problem is the receiver: func (c Card) TopUp. Because Go passes by value, calling card.TopUp(2000) copies the whole card into c, and the method adds 2000 to the copy's balance. Then the method returns, the copy is thrown away, and card in main was never touched. Add a print inside the method to see it happen. Change TopUp to:

func (c Card) TopUp(amount int) {
    c.Balance += amount
    fmt.Println("inside TopUp:", c.Balance)
}


go run .


inside TopUp: 2000
balance after top-up: 0
{C-1042 0 0}


Inside the method the balance really is 2000. It is just the wrong card. Remove the extra print line.

Nothing in the toolchain flags this. It is legal Go, and even go vet has nothing to say about it, because a method that works on its own copy is sometimes exactly what you want. Which kind of receiver to use is a decision you have to make.


Pointer Receivers: Changing the Card Itself

To change the original card, the method needs the card's address, not a copy of its contents. That is a pointer receiver. Change one character in the method's first line, adding * before Card:

func (c *Card) TopUp(amount int) {


go run .


balance after top-up: 2000
{C-1042 2000 0}


The top-up sticks. With (c *Card), the method receives a pointer to the card, and c.Balance += amount follows that pointer to the original card in main and changes its Balance there.

You might be wondering why the call card.TopUp(2000) did not have to change, since card is a Card and the method now wants a *Card. Go handles it for you: when you call a pointer method on a variable, Go automatically takes the variable's address, so card.TopUp(2000) is really (&card).TopUp(2000). Likewise, inside the method, c.Balance with a pointer c is short for (*c).Balance, "the Balance of the value c points to". You write the same dots either way; only the receiver type decides whether the original or a copy is changed.

The rule of thumb that follows: if a method changes the struct, give it a pointer receiver. And since mixing the two kinds on one type is confusing to read, most Go code gives all of a type's methods pointer receivers as soon as one of them needs it.

Try it: Change card := Card{ID: "C-1042"} to card := Card{"C-1042"}, leaving out the field name. Predict whether Go fills in the other fields with zeros, as it did before. It does not: ./main.go:16:23: too few values in struct literal of type Card. A struct literal without field names must list every field, in order, while the Field: value form may list any of them. Use the named form; it keeps working when a field is added later. Put ID: back.


Paying a Fare and Returning an Error

A card also has to pay fares, and paying can fail: an empty card must be refused at the gate. In Go, a function that can fail returns an error as its last result. error is a built-in type, and the value nil means "no error". Replace the whole of main.go with:

package main

import (
    "errors"
    "fmt"
)

const fare = 180 // one trip, in cents

type Card struct {
    ID      string
    Balance int // in cents
    Trips   int
}

func (c *Card) TopUp(amount int) {
    c.Balance += amount
}

func (c *Card) Pay() error {
    if c.Balance < fare {
        return errors.New("not enough balance")
    }
    c.Balance -= fare
    c.Trips++
    return nil
}

func main() {
    card := Card{ID: "C-1042"}
    card.TopUp(500)

    for i := 1; i <= 3; i++ {
        err := card.Pay()
        if err != nil {
            fmt.Println("trip", i, "refused:", err)
            continue
        }
        fmt.Println("trip", i, "paid, balance:", card.Balance)
    }
    fmt.Println(card)
}


go run .


trip 1 paid, balance: 320
trip 2 paid, balance: 140
trip 3 refused: not enough balance
{C-1042 140 2}


A 5.00 EUR top-up pays for two trips at 1.80 EUR, leaving 1.40, and the third trip is refused. The card shows 140 cents and 2 trips. Here is what is new.

  • const fare = 180 declares a constant: a named value fixed when the program is compiled. Using a name instead of writing 180 in several places means the fare is changed in one spot.
  • The import list now has two packages, errors and fmt, in parentheses, one per line.
  • func (c *Card) Pay() error is a pointer method, because it changes Balance and Trips. The error after the parentheses is its result type.
  • if c.Balance < fare { return errors.New("not enough balance") } refuses the trip. errors.New creates an error value carrying that message. Returning immediately means the balance is never touched when the payment fails.
  • c.Balance -= fare and c.Trips++ record the trip, and return nil reports success.
  • In main, for i := 1; i <= 3; i++ tries three trips. err := card.Pay() keeps the result, and if err != nil is the standard Go check: anything other than nil means it failed. Printing err prints its message. continue skips to the next trip without printing "paid".

This "return an error, check it right away" pattern is how Go does almost all error handling. There are no exceptions to forget to catch: the error is an ordinary value, and the caller decides what to do with it.

Try it: Change Pay to a value receiver, func (c Card) Pay() error, and run it. Predict how many trips are refused. None: all three print paid, balance: 500, and the final card is {C-1042 500 0}. Each call checks and changes a fresh copy of a card holding 500 cents, so every payment succeeds and none of them is recorded. Put the * back.


The Same Trap in a for Loop

The system holds many cards, and once a month it gives each one a 2.00 EUR bonus. A slice of cards and a loop look like the natural way to do it. Replace the whole main function with this version, which creates three cards with different balances, applies the bonus, and prints them:

func main() {
    cards := []Card{
        {ID: "C-1042", Balance: 140},
        {ID: "C-1043", Balance: 2600},
        {ID: "C-1044"},
    }

    // Monthly bonus: every card gets 2.00 EUR.
    for _, card := range cards {
        card.TopUp(200)
    }

    for _, card := range cards {
        fmt.Println(card.ID, card.Balance)
    }
}


go run .


C-1042 140
C-1043 2600
C-1044 0


No card got its bonus. TopUp has a pointer receiver now, so it is not the method's fault. The copy is happening one step earlier, in the loop.

for _, card := range cards does not give you the elements of the slice. On each pass it copies the current element into the loop variable card. So card.TopUp(200) correctly changes card, through a pointer to card, but card is a temporary copy that is discarded at the end of the pass. The slice itself is never touched. It is exactly the value-receiver bug again, moved into the for statement.

The fix is to loop over the positions and reach the element inside the slice through its index. Replace the bonus loop with:

    for i := range cards {
        cards[i].TopUp(200)
    }


go run .


C-1042 340
C-1043 2800
C-1044 200


Every card got 200 cents. for i := range cards with a single variable gives only the index: 0, 1, 2. cards[i] is not a copy; it is the element itself, stored in the slice, so cards[i].TopUp(200) passes the address of the real element to the method.

The printing loop, for _, card := range cards, still copies each element, and that is fine there, because it only reads. The rule is about changing things: to modify the elements of a slice of structs, use the index.

Try it: Put the broken for _, card := range cards bonus loop back, and add fmt.Println("inside loop:", card.ID, card.Balance) right after card.TopUp(200). Predict the six lines of output. The first three show 340, 2800 and 200, the bonus applied, and the last three show the old balances, 140, 2600 and 0. The bonus really was added, to copies that disappeared at the end of each pass. Restore the index loop.


A Readable Card With a String Method

The output so far is either raw field values, {C-1042 140 2}, or hand-assembled lines. The support team wants a card to print as an ID, the balance in euros and the trip count. In Go you get that by giving the type a method named String that returns a string. The fmt package checks every value it prints, and if the value has such a method, it calls it.

Add this method above TopUp:

func (c Card) String() string {
    return fmt.Sprintf("%s: %d.%02d EUR, %d trips", c.ID, c.Balance/100, c.Balance%100, c.Trips)
}


Then replace the printing loop at the end of main with a payment attempt on the first two cards, followed by printing each card as it is:

    if err := cards[0].Pay(); err != nil {
        fmt.Println(cards[0].ID, "refused:", err)
    }
    if err := cards[1].Pay(); err != nil {
        fmt.Println(cards[1].ID, "refused:", err)
    }

    for _, card := range cards {
        fmt.Println(card)
    }


go run .


C-1042: 1.60 EUR, 1 trips
C-1043: 26.20 EUR, 1 trips
C-1044: 2.00 EUR, 0 trips


fmt.Println(card) now prints each card through our String method. The first two cards paid a fare, 340 - 180 = 160 and 2800 - 180 = 2620 cents. The third card was not used and keeps its bonus.

String has a value receiver on purpose. It only reads the card, so a copy is fine, and a value receiver means it works both for a Card and for a pointer to one. Inside it, fmt.Sprintf works like Printf but returns the formatted text as a string instead of printing it, which is what String must return. %d.%02d with Balance/100 and Balance%100 turns cents into euros, padding the cents to two digits.

The payments use a short form of the error check: if err := cards[0].Pay(); err != nil { ... }. The part before the ; runs first and declares err, and the condition after it is tested. err then exists only inside that if, which keeps it from leaking into the rest of main.

Note: This is the one place where we break the rule from the pointer-receiver section about not mixing receiver kinds, and it is a common exception. Methods that only describe a value, such as String, are often written with value receivers so they work on both values and pointers.

Try it: Change the String receiver to a pointer, func (c *Card) String() string, and run it. Predict how the cards print. They go back to raw fields, {C-1042 160 1} and so on. The printing loop passes copies of type Card to Println, and a Card value does not have a method that is only defined on *Card, so fmt never finds String. Change it back to (c Card).


Summary

We modelled a transit card with a struct and methods, made top-ups and fares change the real card, refused trips on an empty card with an error, applied a monthly bonus to a whole slice of cards, and gave cards a readable printed form. We deliberately left out persistence and concurrency. A real fare system would store cards in a database and protect them from simultaneous updates, each of which deserves its own tutorial.

  • A struct groups named fields into one type. Prefer the Field: value literal form; fields you leave out get their zero values.
  • Go passes arguments, including method receivers, by value: a struct is copied, and changes to the copy are lost when the method returns.
  • A method that changes its struct needs a pointer receiver, func (c *T). Go takes the address automatically when you call it on a variable, so the call looks the same.
  • Neither the compiler nor go vet warns about a value receiver that modifies its copy; choosing the receiver is your decision.
  • A function that can fail returns an error last, nil means success, and the caller checks if err != nil immediately. errors.New creates an error with a message.
  • for _, x := range slice copies each element into x. To modify elements of a slice of structs, loop with for i := range slice and use slice[i].
  • A method String() string controls how fmt prints a type. Give it a value receiver, so that values as well as pointers print through it.
  • fmt.Sprintf formats like Printf but returns the result as a string.

You need to be logged in to access the cloud lab.

Log in