Go course Lesson 5 of 6

Go from zero: a method can change the struct

A method with a pointer receiver changes the struct the caller holds. AddTip adds 20 percent to a $4.50 bill, and the program prints $5.40.

Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.

Back to top

The Label method in lesson 2 only read the struct. It took Item by value, so it saw a copy. A method that must change the struct takes a pointer. The pointer is the address of the one bill the caller holds. AddTip is that method: it adds a tip to the cents already on the bill.

The pointer is which bill you mean#

A value receiver gets a copy of the struct. Changing the copy does not change the caller, and the program still looks successful. A pointer receiver gets the address, so the assignment writes the field of the bill main is holding. &Bill{cents: 450} makes the bill and takes that address in one step. Twenty percent of 450 is 90, because 450 * 20 / 100 is integer arithmetic and the division happens after the multiply. The bill becomes 540 cents, which prints as $5.40.

The same bill, after the tip
  1. start450
  2. AddTip(20)540
package main

import "fmt"

type Bill struct {
    cents int
}

func (b *Bill) AddTip(percent int) {
    b.cents = b.cents + b.cents*percent/100
}

func main() {
    b := &Bill{cents: 450}
    b.AddTip(20)
    fmt.Printf("$%d.%02d\n", b.cents/100, b.cents%100)
}
$5.40

The star is the pointer#

*Bill means a pointer to a Bill. b := &Bill{cents: 450} makes a bill and takes its address. b.AddTip(20) calls the method. Inside AddTip, the new cents are the old cents plus the tip, and that sum is stored back into the same bill.

If the receiver were (b Bill) with no star, AddTip would change a copy and main would still print $4.50. The program would run. The customer would be undercharged. The star is how you say the method is allowed to change the caller's bill.

Call it on the pointer you made#

&Bill{cents: 450} is the whole construction. You do not need a named constructor for a struct this small. What you do need is the pointer at the start, because AddTip asks for one. Go will take the address for you if you have a Bill variable and call AddTip on it. This lesson makes the pointer itself so the type of b matches the receiver. The next lesson says a function can accept any struct that has the method it needs.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.