These are the notes for Go episode 20. In episode 19 Raju's chai stall got a Bill struct and a separate total(b Bill) function to add it up. Today Raju needs a second total, the names collide, and fixing that you will invent Go's methods. You will learn why Go has no overloading, the method declaration and its receiver, value receivers (which change a copy) and pointer receivers (which change the original), Go's automatic address-of and automatic dereference, addressable values, method sets, methods on non-struct types like Rupees, a first look at String() and fmt.Stringer, constructor functions (NewBill), method values and method expressions, the receiver consistency rule, and encapsulation with unexported fields. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs, compiler errors and panics are from real runs of go run main.go (Go 1.24), with temporary folder paths shortened to /tmp/....
The problem: two staff members called "total"
Raju now needs two totals: the amount of one order (quantity × rate) and the total of the whole bill. Both are naturally called total. It's like a stall with two staff members both named "Total": Raju shouts "Total!", and who should answer?
package main
import "fmt"
type Order struct {
Item string
Qty int
Rate float64
}
type Bill struct{ Orders []Order }
func total(o Order) float64 { return float64(o.Qty) * o.Rate }
func total(b Bill) (sum float64) {
for _, o := range b.Orders {
sum += total(o)
}
return
}
func main() {
b := Bill{[]Order{{"chai", 3, 12.5}, {"samosa", 2, 15}}}
fmt.Println(total(b))
}
# command-line-arguments
./main.go:15:6: total redeclared in this block
./main.go:13:6: other declaration of total
./main.go:24:23: cannot use b (variable of struct type Bill) as Order value in argument to total
- Redeclared means "declared a second time". A block here is the whole package: inside one package, a function name can be declared only once.
- Overloading is a feature of languages like Java and C++: several functions share one name and the compiler picks one by the types of the arguments. Go has no overloading, on purpose: a name always means exactly one thing, so code is easier to read.
- The second error follows from the first: Go keeps the first
total(the one taking anOrder), sototal(b)with aBillis a type mismatch. We could invent names likeorderTotalandbillTotal, but every new type adds more prefixes. There's a better way: ask the thing itself.
Ask the thing itself: methods and receivers
At the stall, instead of one person computing every total, Raju asks the order card "what's your amount?" and the bill "what's your total?". Each thing knows its own numbers.
| At the stall | In Go | Name |
|---|---|---|
| "Order card, your amount?" | func (o Order) Amount() |
a method: a function attached to a type |
| The card being asked | (o Order) |
the receiver: the value the method works on |
| Ask with a dot | o.Amount() |
a method call: value.Method() |
package main
import "fmt"
type Order struct {
Item string
Qty int
Rate float64
}
type Bill struct{ Orders []Order }
func (o Order) Amount() float64 { return float64(o.Qty) * o.Rate }
func (b Bill) Total() (sum float64) {
for _, o := range b.Orders {
sum += o.Amount()
}
return
}
func main() {
b := Bill{[]Order{{"chai", 3, 12.5}, {"samosa", 2, 15}}}
fmt.Println(b.Orders[0].Amount(), b.Total())
}
37.5 67.5
- A method is a function that belongs to a type. You call it with a dot on a value of that type, just like reading a field, but with brackets:
b.Total(). - A method declaration is
func, then the receiver in brackets, then the method's name, parameters and results:func (o Order) Amount() float64 { ... }. - The receiver
(o Order)is a special parameter written before the name. Inside the method,ois the order being asked. Inb.Orders[0].Amount(), the receiver isb.Orders[0]. - The receiver type is the type after the receiver's name, here
Order. It decides which type the method belongs to:Amountis "a method ofOrder", writtenOrder.Amount. Totaluses a named result(sum float64)and a barereturn(episode 9):sumstarts at 0 and is returned at the end. The method must be declared in the same package as its receiver type, at the top level (not insidemain).- Under the hood a method is just a function whose first argument is the receiver:
b.Total()works likeBill.Total(b)(a method expression, shown later). The dot syntax lets every type have its own names.
Methods with the same name on different types
Because each method belongs to its type, Order and Bill can both have a method called Total: rename Amount to Total in the program above (sum += o.Total() inside Bill.Total) and it compiles and prints the same 37.5 67.5 (real run). Go chooses the method by the type of the value before the dot, not by argument types. This is not overloading: one type still can't have two methods named Total (see Common mistakes).
Naming the receiver
The Go convention (from the official Go Code Review Comments): use a short name, usually one or two letters from the type: o for Order, b for Bill, k for Khata. Be consistent: every method of Bill uses b, so readers never wonder whether b and bill are different things. Don't use this or self (from Java, C++, Python). In Go the receiver is just an ordinary parameter, and naming it like one makes that clear.
Value receivers change a copy
Raju wants the bill to add items to itself. A new Bill with Items and Sum, and an Add method:
package main
import "fmt"
type Bill struct {
Items []string
Sum float64
}
func (b Bill) Add(item string, rate float64) {
b.Items = append(b.Items, item)
b.Sum += rate
}
func main() {
var b Bill
b.Add("chai", 12.5)
b.Add("samosa", 15)
fmt.Println(len(b.Items), b.Sum)
}
0 0
The bill is still empty! Remember episode 19: assigning a struct copies it, and passing it to a function copies it too. (b Bill) is a value receiver: the receiver type is the plain type Bill, so Add gets its own copy of the bill, changes the copy, and the copy is thrown away when Add returns. No error, no warning: just a wrong answer.
Pointer receivers: a photocopy vs the real bill book
| At the counter | In Go | Name |
|---|---|---|
| The cashier writes on a photocopy of the bill: readable, but the real book stays blank | func (b Bill) Add |
value receiver: works on a copy |
| Hand over the real bill book itself, so writing goes into it | func (b *Bill) Add |
pointer receiver: works on the original |
A pointer receiver has a pointer type, *Bill (episode 11: a pointer holds the address of a value). The method receives the address of the original bill, so its changes are real. One character changes:
package main
import "fmt"
type Bill struct {
Items []string
Sum float64
}
func (b *Bill) Add(item string, rate float64) {
b.Items = append(b.Items, item)
b.Sum += rate
}
func main() {
var b Bill
b.Add("chai", 12.5) // Go does (&b).Add
b.Add("samosa", 15)
fmt.Println(len(b.Items), b.Sum)
p := &b
p.Add("bun maska", 35)
fmt.Println(p.Items, b.Sum)
}
2 27.5
[chai samosa bun maska] 62.5
- Inside
Add,bis now a*Bill, yet we still writeb.Items, not(*b).Items. Go dereferences the pointer for you when you use a field through it (episode 19). To dereference means to go from the address to the value stored there. - Look at the call:
b.Add(...), butbis aBill, not a pointer. Go sees thatAddneeds a*Billand thatbis a variable, so it quietly calls(&b).Add(...). This is automatic address-of: Go takes the address for you. - It works the other way too:
pis a*Bill, andp.Addsimply works. IfAddhad a value receiver, Go would call(*p).Add(...)for you: automatic dereference at the call. So you rarely write&or*at a call site. The receiver type in the declaration decides copy or original; the call looks the same either way.
Method sets: when Go can't take the address
Go can only take an address if the value has one.
package main
import "fmt"
type Bill struct {
Items []string
Sum float64
}
func (b *Bill) Add(item string, rate float64) {
b.Items = append(b.Items, item)
b.Sum += rate
}
func main() {
tables := map[int]Bill{4: {}}
tables[4].Add("chai", 12.5)
Bill{}.Add("samosa", 15)
fmt.Println(tables)
}
# command-line-arguments
./main.go:17:15: cannot call pointer method Add on Bill
./main.go:19:12: cannot call pointer method Add on Bill
- A pointer method is a method with a pointer receiver. An addressable value is one you can take the address of with
&: a variable, a slice element (s[i]), a field of an addressable struct (b.Order), or anything reached through a pointer (*p,p.Field). - Not addressable: a map element (
tables[4]): maps move their entries around in memory as they grow, so Go never gives out an entry's address. A literal written straight in the code (Bill{}), a function's result (newBill()), and a constant have no fixed place either. - No address, so no automatic
&, so no pointer methods. (&Bill{}is a special case Go allows: it creates a new variable and gives its address.)
The usual fix is a map of pointers. Slice elements are already addressable. Same Bill and Add as above, new main:
func main() {
tables := map[int]*Bill{4: {}}
tables[4].Add("chai", 12.5)
tables[4].Add("samosa", 15)
fmt.Println(tables[4].Items, tables[4].Sum)
bills := []Bill{{}, {}}
bills[1].Add("bun maska", 35) // slice elements are addressable
fmt.Println(bills[1].Sum)
}
[chai samosa] 27.5
35
(In map[int]*Bill{4: {}}, the {} is short for &Bill{}: Go fills in the element type.)
The rule: method sets of T and *T
The method set of a type is the list of methods that values of that type have.
| Type | Its method set | Example |
|---|---|---|
Bill (value type T) |
only methods with a value receiver (b Bill) |
Total |
*Bill (pointer type *T) |
methods with value receivers and pointer receivers | Total and Add |
*Billhas both because from a pointer Go can always reach the value (*p), but from a value it can't always get an address. Callingb.Add()on a variable of typeBillis only a convenience: the variable is addressable, so Go adds&. Strictly,Addis not inBill's method set.- Method sets matter most in episode 21: they decide which interfaces a type satisfies. A small preview,
fmtlooks for aString()method using the method set of the value you pass:
type Bill struct{ Sum float64 }
func (b *Bill) String() string { return fmt.Sprintf("Bill(Rs %.2f)", b.Sum) }
func main() {
b := Bill{Sum: 27.5}
fmt.Println(b)
fmt.Println(&b)
}
{27.5}
Bill(Rs 27.50)
String has a pointer receiver, so it is in the method set of *Bill only. Println(b) gets a plain Bill (a copy, with no address), doesn't find String, and prints the fields. Println(&b) finds it.
Methods on any type you define: Rupees
Methods aren't only for structs. Any defined type in your package can have them (a defined type is one made with type Name Underlying, episode 19). Episode 19's Rupees, whose underlying type is float64, gets a String method that formats it and a WithGST method that adds 5% tax:
package main
import "fmt"
type Rupees float64
func (r Rupees) String() string {
return fmt.Sprintf("Rs %.2f", float64(r))
}
func (r Rupees) WithGST() Rupees { return r * 1.05 }
func main() {
price := Rupees(100)
fmt.Println(price.String())
fmt.Println(price, price.WithGST())
fmt.Printf("%v %.1f\n", price, price)
}
Rs 100.00
Rs 100.00 Rs 105.00
Rs 100.00 100.0
- Inside
String,float64(r)converts the receiver back to a plainfloat64before formatting (why this matters is shown below).Rupeesis a small value that never changes inside its methods, so a value receiver is right: copying 8 bytes is free. r * 1.05: arithmetic works because the underlying type isfloat64, and the untyped constant1.05becomes aRupees.- Line 2 is the surprise:
fmt.Println(price)printedRs 100.00by itself. Thefmtpackage checks every value: "does it have a methodString() string?" If yes, it calls it. A type with such a method is called afmt.Stringer; that's an interface, covered properly in episode 21.%vand%suseString(). But%.1fstill treatspriceas a number (100.0): the float verbs format the underlying value. - Other non-struct types work the same way:
type Orders []Ordercan havefunc (s Orders) Total() float64(practice 2), andtype Menu map[string]Rupeescan have aPrice(item string)method.
Only your own types: local vs non-local
Can we add a method to float64 itself?
package main
import "fmt"
func (f float64) Double() float64 { return f * 2 }
func main() {
fmt.Println(2.5)
}
# command-line-arguments
./main.go:5:9: cannot define new methods on non-local type float64
- A local type is a type declared in your own package. A non-local type comes from somewhere else: a built-in type like
float64orstring, or another package's type liketime.Duration. You can only add methods to local types. Otherwise two packages could both add aDoublemethod tofloat64and nobody would know which one runs. The fix is what we already did: define your own type (type Amount float64) and give it methods.
A defined type does not inherit methods
Episode 19 said a new defined type gets the underlying type, not the methods. Here is that rule with real methods:
package main
import "fmt"
type Bill struct{ Sum float64 }
func (b Bill) Total() float64 { return b.Sum }
type B Bill
func main() {
x := B{Sum: 50}
fmt.Println(x.Total())
}
# command-line-arguments
./main.go:13:19: x.Total undefined (type B has no field or method Total)
type B Bill copies Bill's fields (its underlying struct type) but starts with an empty method set. To use Total, convert: Bill(x).Total(). A type alias type Alias = Bill is just another name for Bill, so it keeps every method: with it added, fmt.Println(Bill(x).Total()) prints 50 and var a Alias = Bill{Sum: 20}; fmt.Println(a.Total()) prints 20 (real run).
The String() trap: infinite recursion
Why did String write float64(r) instead of just r? Change the method to this (line 8 is the return) and run fmt.Println(Rupees(100)):
func (r Rupees) String() string {
return fmt.Sprintf("%v", r)
}
%v on a Rupees calls... r.String(), which calls Sprintf("%v", r), which calls r.String() again, forever. This is infinite recursion (a function calling itself with no way to stop). Each call uses a little stack memory, until Go stops the program. The first lines of the real output (the full trace is thousands of lines):
runtime: goroutine stack exceeds 1000000000-byte limit
runtime: sp=0xc0200e0380 stack=[0xc0200e0000, 0xc0400e0000]
fatal error: stack overflow
go vet main.go catches it before you run (real output):
# command-line-arguments
# [command-line-arguments]
./main.go:8:12: fmt.Sprintf format %v with arg r causes recursive (command-line-arguments.Rupees).String method call
Fix: convert to the underlying type first, float64(r). A float64 has no String method, so the recursion stops.
Constructors: NewBill
Now a Bill that counts how many of each item were ordered, in a map. We use the zero value, var b Bill:
package main
import "fmt"
type Bill struct {
Table int
Counts map[string]int
}
func (b *Bill) Add(item string) { b.Counts[item]++ }
func main() {
var b Bill
b.Add("chai")
fmt.Println(b.Counts)
}
panic: assignment to entry in nil map
goroutine 1 [running]:
main.(*Bill).Add(...)
/tmp/.../main.go:10
main.main()
/tmp/.../main.go:14 +0x2f
exit status 2
- The zero value of a map field is a nil map: a map variable that was never created with
makeor a literal. You can read a nil map (it acts empty) but writing to it panics (episode 15). So the zero value of thisBillis not ready to use. Note how the trace names the method:main.(*Bill).Add= methodAddwith receiver type*Billin packagemain.
| Stationery shop | In Go |
|---|---|
| Loose pages: no binding, no numbers, no carbon paper. Not ready. | var b Bill: nil map inside |
| A ready bill book: bound, numbered, carbon in. Write immediately. | NewBill(4): returns a ready *Bill |
Go has no constructor keyword (no new Bill() with special code like Java). Instead, by convention, you write an ordinary function named New + the type name that builds a ready value and returns it, usually as a pointer. That's a constructor function.
package main
import "fmt"
type Bill struct {
Table int
Counts map[string]int
}
func (b *Bill) Add(item string) { b.Counts[item]++ }
func NewBill(table int) *Bill {
return &Bill{Table: table, Counts: map[string]int{}}
}
func main() {
b := NewBill(4)
b.Add("chai")
b.Add("chai")
b.Add("samosa")
fmt.Println(b.Table, b.Counts)
}
4 map[chai:2 samosa:1]
&Bill{Table: table, Counts: map[string]int{}}is a keyed literal (episode 19) with&in front: it creates a newBilland gives its address. Naming:NewBill(exported, other packages can call it);newBillif it's private to the package; justNewwhen the package has one main type (list.New()incontainer/list,errors.New).- Constructors are also the place to check inputs and fill in defaults (practice 3). Not every type needs one. If the zero value is already useful (like
strings.Builder,sync.Mutex, or theCounterbelow), skip the constructor; "make the zero value useful" is a Go proverb. - Don't confuse it with the built-in
new(Bill): that only allocates a zeroedBilland returns*Bill; the map would still be nil.
Why returning a pointer from NewBill is safe
In C, returning the address of a local value is a classic bug: the memory is freed when the function returns. In Go the compiler's escape analysis checks whether a value is still used after the function returns ("escapes"). If it does, the value is put on the heap (memory that lives as long as something points to it, cleaned up by the garbage collector) instead of the function's stack (memory freed on return). A tiny example:
package main
import "fmt"
type Bill struct {
Table int
Counts map[string]int
}
func NewBill(table int) *Bill {
return &Bill{Table: table, Counts: map[string]int{}}
}
func main() {
b := NewBill(4)
fmt.Println(b.Table)
}
It prints 4. go build -gcflags=-m main.go prints the compiler's decisions (real output):
# command-line-arguments
./main.go:10:6: can inline NewBill
./main.go:15:17: inlining call to NewBill
./main.go:16:16: inlining call to fmt.Println
./main.go:11:12: &Bill{...} escapes to heap
./main.go:11:54: map[string]int{} escapes to heap
./main.go:15:17: &Bill{...} does not escape
./main.go:15:17: map[string]int{} does not escape
./main.go:16:16: ... argument does not escape
./main.go:16:18: b.Table escapes to heap
- Line 11 (inside
NewBill):&Bill{...} escapes to heap. Compiled on its own,NewBillhands its bill to the caller, so it goes on the heap. Always safe. On line 15 (the call inmain):NewBillis so small that the compiler inlines it (pastes its body intomain), sees the bill never leavesmain, and keeps it on the stack:does not escape. You get safety and speed without doing anything. b.Table escapes to heapcomes fromfmt.Println, which takes its arguments as interfaces.
Method values and method expressions
Raju counts chai cups with a tally counter (a clicker).
| At the stall | In Go | Name |
|---|---|---|
| Raju hands his own clicker to a helper; the helper clicks, Raju's count goes up | tap := c.Tap |
method value: the method already tied to its receiver |
| A card: "how to click a clicker: bring any clicker" | (*Counter).Tap |
method expression: the receiver becomes the first argument |
package main
import "fmt"
type Counter struct{ n int }
func (c *Counter) Tap() { c.n++ }
func repeat(n int, f func()) {
for range n {
f()
}
}
func main() {
var c Counter
tap := c.Tap // a method value, bound to c
tap()
repeat(3, c.Tap)
fmt.Println(c.n)
tapOf := (*Counter).Tap // a method expression
tapOf(&c)
fmt.Println(c.n)
fmt.Printf("%T | %T\n", tap, tapOf)
}
4
5
func() | func(*main.Counter)
- A function value (episode 9) is a function stored in a variable or passed as an argument, like
f func()inrepeat. (for range n, Go 1.22+, repeats the loop bodyntimes.) c.Tapwithout brackets is a method value: a function value with the receiver already bound (attached). Here Go binds&c(automatic address-of again). Its type isfunc(): no receiver argument left. Sotap()and the three calls insiderepeatall clickc: 1 + 3 = 4.(*Counter).Tapis a method expression: the type, a dot, the method name. It turns the method into a plain function whose first parameter is the receiver: typefunc(*main.Counter). You pass the counter yourself:tapOf(&c)→ 5. The brackets are needed:*Counter.Tapwould mean "dereferenceCounter.Tap".- For a value-receiver method, write the expression with the plain type:
Rupees.WithGSThas typefunc(main.Rupees) main.Rupees. Because*T's method set includes value methods,(*Rupees).WithGSTalso exists. With theRupeestype from above (real run):
gst := Rupees.WithGST
fmt.Println(gst(100))
fmt.Printf("%T\n", gst)
fmt.Printf("%T\n", (*Rupees).WithGST)
105
func(main.Rupees) main.Rupees
func(*main.Rupees) main.Rupees
Method values are used all the time: http.HandleFunc("/", s.handleHome), defer f.Close(), strings.Map(r.replace, text), sort.Slice callbacks.
Expert: a method value copies the receiver when it is created
The receiver is evaluated and saved at the moment you write r.String, not when you call it later:
With Rupees (and its String) from above, plus type Counter struct{ n int } and func (c *Counter) Count() int { return c.n }:
func main() {
r := Rupees(100)
show := r.String // receiver r is copied NOW
r = 200
fmt.Println(show(), r)
var c Counter
get := c.Count // receiver &c is saved NOW
c.n = 7
fmt.Println(get())
}
Rs 100.00 Rs 200.00
7
Stringhas a value receiver, soshowholds a copy ofrtaken when it was created (100). Changingrlater doesn't affect it.Counthas a pointer receiver, sogetholds the address&c. It sees later changes (7).- The same rule applies to
defer r.Print()andgo c.Run(): the receiver is evaluated immediately.
Choosing receivers: value or pointer?
- Value receiver
(r T): the method gets a copy. Use it for small values that never change (Rupees,time.Time, aPoint{X, Y}). Safe to call on map elements and literals. - Pointer receiver
(r *T): the method sees the original. Use it when the method changes the receiver (Add,Buy,Tap), when the struct is big (copying would be slow), or when it must not be copied (it contains async.Mutex, episode 28).
The receiver consistency rule: if any method of a type needs a pointer receiver, give all its methods pointer receivers (even read-only ones like Total or Balance). Then everyone treats the type the same way (always through a *T), the method set of *T is the complete set, and nobody accidentally copies a value whose other methods expect to share state. When unsure, choose a pointer receiver.
Expert corner: calling methods on a nil pointer
A method with a pointer receiver can be called on a nil pointer (a pointer that points to nothing). The call itself is fine; it only panics if the method reads through the nil pointer. That makes "nil means empty" possible:
package main
import "fmt"
type Node struct {
Item string
Next *Node
}
func (n *Node) Len() int {
if n == nil {
return 0
}
return 1 + n.Next.Len()
}
func main() {
var empty *Node
fmt.Println(empty.Len())
queue := &Node{"chai", &Node{"samosa", nil}}
fmt.Println(queue.Len())
}
0
2
empty.Len()runsLenwithn == nil, which returns 0. Andn.Next.Len()on the last node also callsLenwith nil: the check ends the recursion neatly. This is how linked lists and trees (episodes 47+) often handle "no node". Also useful for empty lists/trees, optional configuration (var cfg *Config; cfg.Timeout()returns a default), and loggers wherenilmeans "log nothing".
Without the nil check, reading a field through a nil pointer panics: var b *Bill; b.Total() with return b.Sum gives panic: runtime error: invalid memory address or nil pointer dereference, and the trace names main.(*Bill).Total(...) (real run). A value-receiver method called through a nil pointer always panics, because Go must dereference the pointer to make the copy.
Mini project: Asha's khata
A khata is the credit notebook a shop keeps for regular customers: what they bought on credit, what they paid, and what they still owe.
package main
import "fmt"
type Khata struct {
name string
balance float64
}
func NewKhata(name string) *Khata { return &Khata{name: name} }
func (k *Khata) Buy(amt float64) { k.balance += amt }
func (k *Khata) Pay(amt float64) { k.balance -= amt }
func (k *Khata) Balance() float64 { return k.balance }
func main() {
k := NewKhata("Asha")
k.Buy(37.5)
k.Buy(30)
k.Pay(50)
fmt.Printf("%s owes Rs %.2f\n", k.name, k.Balance())
}
Asha owes Rs 17.50
- The fields
nameandbalancestart with a lowercase letter, so they are unexported (episode 19): code in other packages can't touch them. The only way to change the balance is throughBuyandPay. Hiding data behind methods like this is called encapsulation. (Inside packagemain, as here,k.namestill works; the protection is between packages.) Balance()is a getter: a method that just returns a hidden field. Go style names itBalance, notGetBalance.NewKhatais the constructor; all methods use pointer receivers, following the consistency rule (evenBalance).
Extended version: History() and String()
The video's homework: keep every entry in a slice field, and add a History method. We also give *Khata a String method so fmt.Println(k) prints a summary.
package main
import "fmt"
type entry struct {
kind string
amt float64
}
type Khata struct {
name string
balance float64
entries []entry
}
func NewKhata(name string) *Khata { return &Khata{name: name} }
func (k *Khata) Buy(amt float64) {
k.balance += amt
k.entries = append(k.entries, entry{"buy", amt})
}
func (k *Khata) Pay(amt float64) {
k.balance -= amt
k.entries = append(k.entries, entry{"pay", amt})
}
func (k *Khata) History() []string {
lines := make([]string, 0, len(k.entries))
for i, e := range k.entries {
lines = append(lines, fmt.Sprintf("%d. %-3s Rs %6.2f", i+1, e.kind, e.amt))
}
return lines
}
func (k *Khata) String() string {
return fmt.Sprintf("%s owes Rs %.2f", k.name, k.balance)
}
func main() {
k := NewKhata("Asha")
k.Buy(37.5)
k.Buy(30)
k.Pay(50)
for _, line := range k.History() {
fmt.Println(line)
}
fmt.Println(k)
}
1. buy Rs 37.50
2. buy Rs 30.00
3. pay Rs 50.00
Asha owes Rs 17.50
entryis lowercase too: an unexported type, an internal detail.Historybuilds a new slice each time, so a caller who changes it can't change the real record. If it returnedk.entriesdirectly, the caller would share the khata's backing array (episode 13). Returning copies of internal slices is part of good encapsulation.fmt.Println(k)works becausekis a*KhataandStringis in*Khata's method set.- Try it: make
Payrefuse amounts greater than the balance, and addEntries() int.
The next problem: Raju wants one function, printReceipt, that works for a Bill and a Khata, since both can report a total. But a function parameter has one type. How can a function accept anything that has the right method? Episode 21: interfaces.
Common mistakes (and the real messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
func total(o Order) and func total(b Bill) |
total redeclared in this block |
methods: o.Amount(), b.Total() |
func (b Bill) Add(...) { b.Sum += r } |
no error; the bill stays 0 0 |
pointer receiver func (b *Bill) Add |
tables[4].Add(...) with map[int]Bill |
cannot call pointer method Add on Bill |
map[int]*Bill, or copy out, change, store back |
Bill{}.Add(...) |
cannot call pointer method Add on Bill |
use a variable, or (&Bill{}).Add(...) |
func (f float64) Double() float64 |
cannot define new methods on non-local type float64 |
type Amount float64 |
type B Bill; x.Total() |
x.Total undefined (type B has no field or method Total) |
Bill(x).Total() or an alias |
func (b **Bill) Reset() |
invalid receiver type **Bill |
receiver *Bill |
func (p Printer) Hello() (Printer is an interface) |
invalid receiver type Printer (pointer or interface type) |
methods go on concrete types |
type BillPtr *Bill; func (p BillPtr) Reset() |
invalid receiver type BillPtr (pointer or interface type) |
use *Bill as the receiver |
field Total and method Total on one type |
field and method with the same name Total |
rename one: field Sum, method Total() |
two Total methods with different parameters |
method Bill.Total already declared at ./main.go:5:15 |
different names: Total, TotalWithGST |
func (b Bill) Total() and func (b *Bill) Total() |
method Bill.Total already declared at ./main.go:5:15 |
one receiver kind per method name |
Bill.Total() (no receiver) |
not enough arguments in call to Bill.Total / have () / want (Bill) |
b.Total(), or Bill.Total(b) |
Bill.Add when Add has a *Bill receiver |
invalid method expression Bill.Add (needs pointer receiver (*Bill).Add) |
(*Bill).Add |
String() returning fmt.Sprintf("%v", r) |
fatal error: stack overflow; vet: causes recursive ... String method call |
fmt.Sprintf("%.2f", float64(r)) |
var b *Bill; b.Total() reading b.Sum |
panic: runtime error: invalid memory address or nil pointer dereference |
check if b == nil, or create the bill |
String() with a pointer receiver, fmt.Println(b) |
prints {27.5}, String not used |
fmt.Println(&b) or a value receiver |
All messages above are from real runs (go run main.go, Go 1.24). The field-and-method error comes with a second line, other declaration of Total, and Bill.Total() prints have () / want (Bill) on two more lines: Bill.Total is a method expression, a function func(Bill) float64, so it needs the receiver as its argument (Bill.Total(b) works).
Practice
- Write
type Celsius float64with aString()method that prints85.0°Cand aFahrenheit()method. Print 85 °C (chai temperature) withPrintlnand with%v,%sand%.0f. - Give a slice type
type Orders []OrderaTotal()method, so one table's orders can add themselves up. - Write
NewKhata(name string) (*Khata, bool)that refuses an empty or all-spaces name (returningnil, false). - Pass a method value
asha.Buyto a functioneach(amounts []float64, f func(float64)). - Fix
tables[4].Add(...)formap[int]Billwithout changing the map tomap[int]*Bill. - Make
(*Khata).Balancesafe to call on thenilfrom a refusedNewKhata, and on a missing key ofmap[string]*Khata.
Solution
- A value receiver: a temperature is a small value that never changes.
package main
import "fmt"
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
func (c Celsius) Fahrenheit() float64 { return float64(c)*9/5 + 32 }
func main() {
chai := Celsius(85)
fmt.Println(chai, chai.Fahrenheit())
fmt.Printf("%v | %s | %.0f\n", chai, chai, chai)
}
85.0°C 185
85.0°C | 85.0°C | 85
- Methods work on any local defined type, including slices. A value receiver is fine:
Totalonly reads.
package main
import "fmt"
type Order struct {
Item string
Qty int
Rate float64
}
type Orders []Order
func (s Orders) Total() (sum float64) {
for _, o := range s {
sum += float64(o.Qty) * o.Rate
}
return
}
func main() {
table4 := Orders{{"chai", 3, 12.5}, {"samosa", 2, 15}}
fmt.Println(len(table4), table4.Total())
}
2 67.5
3 and 6 (one program). Practice 3 uses the "comma ok" result, like a map lookup (episode 15); episode 24 shows the more common (*Khata, error) form. For practice 6, a refused NewKhata and a missing map key both give a nil *Khata, and the nil check makes Balance return 0 instead of panicking.
package main
import (
"fmt"
"strings"
)
type Khata struct {
name string
balance float64
}
func NewKhata(name string) (*Khata, bool) {
name = strings.TrimSpace(name)
if name == "" {
return nil, false
}
return &Khata{name: name}, true
}
func (k *Khata) Buy(amt float64) { k.balance += amt }
func (k *Khata) Balance() float64 {
if k == nil {
return 0
}
return k.balance
}
func main() {
for _, n := range []string{"Asha", " "} {
k, ok := NewKhata(n)
if ok {
k.Buy(17.5)
}
fmt.Printf("%q ok=%t balance=%.2f\n", n, ok, k.Balance())
}
books := map[string]*Khata{}
fmt.Println(books["Ravi"].Balance()) // missing key: nil *Khata
}
"Asha" ok=true balance=17.50
" " ok=false balance=0.00
0
asha.Buyandravi.Buyare bothfunc(float64), each bound to its own khata.
package main
import "fmt"
type Khata struct{ balance float64 }
func (k *Khata) Buy(amt float64) { k.balance += amt }
func each(amounts []float64, f func(float64)) {
for _, a := range amounts {
f(a)
}
}
func main() {
var asha, ravi Khata
each([]float64{37.5, 30}, asha.Buy)
each([]float64{12.5}, ravi.Buy)
fmt.Println(asha.balance, ravi.balance)
}
67.5 12.5
- A local variable
bis addressable, sob.Addworks; then store the changed copy back.
package main
import "fmt"
type Bill struct{ Sum float64 }
func (b *Bill) Add(rate float64) { b.Sum += rate }
func main() {
// copy out, change, store back
plain := map[int]Bill{7: {}}
b := plain[7]
b.Add(15)
plain[7] = b
fmt.Println(plain[7].Sum)
}
15
Quick quiz
1. What does this print? (From the video.)
type Cup struct{ ml int }
func (c Cup) Fill() { c.ml = 150 }
func (c *Cup) Refill() { c.ml = 200 }
func main() {
var c Cup
c.Fill()
fmt.Print(c.ml, " ")
c.Refill()
fmt.Println(c.ml)
}
- A.
150 200 - B.
0 200 - C.
0 0 - D. compile error
Answer
B. 0 200 (real output). Fill has a value receiver, so it fills a copy and c.ml stays 0. Refill has a pointer receiver; c is an addressable variable, so Go calls (&c).Refill() and the real cup becomes 200.
2. Add has a *Bill receiver. Which call does not compile: var b Bill; b.Add(...), bills[0].Add(...) on a []Bill, or tables[4].Add(...) on a map[int]Bill?
Answer
tables[4].Add(...): cannot call pointer method Add on Bill. Map elements are not addressable, so Go can't add the &. Variables and slice elements are addressable.
3. type B Bill, and Bill has a Total() method. Does x := B{Sum: 50}; x.Total() compile?
Answer
No: x.Total undefined (type B has no field or method Total). A defined type gets the underlying type's fields, not its methods. Bill(x).Total() works, and an alias type B = Bill would keep the methods.
4. What does fmt.Printf("%T\n", (*Counter).Tap) print, where func (c *Counter) Tap()?
Answer
func(*main.Counter). A method expression turns the receiver into the first parameter. The method value c.Tap would print func().
5. r := Rupees(100); show := r.String; r = 200; fmt.Println(show()), with String on a value receiver. What is printed?
Answer
Rs 100.00. A method value evaluates and copies a value receiver when it is created. With a pointer receiver it would save &r and print Rs 200.00.
Interview questions
1. What is a method in Go, and how is it different from a function?
A method is a function with a receiver: a special parameter written before the name, func (b Bill) Total() float64. It belongs to the receiver's type and is called with a dot, b.Total(). Under the hood it is a function whose first argument is the receiver (Bill.Total(b) is a valid call). Methods let each type have its own names, and they make up the method sets that interfaces check.
2. Does Go support function or method overloading? What do you do instead?
No. A name can be declared once per package (total redeclared in this block), and a type can have only one method with a given name (method Bill.Total already declared). Instead you use methods on different types (o.Total(), b.Total()), different descriptive names (Total, TotalWithGST), variadic parameters, or (from episode 21) interfaces.
3. Value receiver or pointer receiver: how do you choose?
Pointer receiver if the method modifies the receiver, if the struct is large, or if it must not be copied (contains a sync.Mutex). Value receiver for small, immutable values like time.Time or a Rupees amount. Consistency rule: if any method needs a pointer receiver, make all of them pointer receivers. When in doubt, use a pointer.
4. Why can you call a pointer method on a variable b but not on m[k] or Bill{}?
For b.Add() Go automatically rewrites the call to (&b).Add(), which needs an addressable value. Variables, slice elements, fields of addressable structs and pointer dereferences are addressable; map elements (maps may move entries when they grow), literals and function results are not, so you get cannot call pointer method Add on Bill. Fix with a map[K]*Bill or by copying out, modifying and storing back.
5. What are the method sets of T and *T, and why do they matter?
The method set of T contains the methods with value receivers; that of *T contains both value and pointer receiver methods. They decide which interfaces a type implements: if String() has a pointer receiver, a Bill value is not a fmt.Stringer but *Bill is, which is why fmt.Println(b) printed {27.5} and fmt.Println(&b) used String.
6. What is the difference between a method value and a method expression?
A method value c.Tap binds the receiver immediately and gives a function of the remaining parameters (func()); for a value receiver the receiver is copied at that moment. A method expression (*Counter).Tap names the method on the type and gives a function whose first parameter is the receiver (func(*Counter)). Method values are common as callbacks: http.HandleFunc("/", s.home).
7. Go has no constructors. How do you create a ready-to-use value?
By convention, a function NewX(...) *X (or New when the package has one main type) that initialises maps, checks inputs and sets defaults, then returns &X{...}. Returning a pointer to a local value is safe because escape analysis moves it to the heap when it outlives the function. If the zero value is already useful, no constructor is needed.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Method | a function attached to a type, called with a dot | b.Total() |
| Method declaration | func, receiver, name, parameters, results, body |
func (o Order) Amount() float64 { ... } |
| Receiver | the special parameter before the method name; the value the method works on | (o Order) |
| Receiver type | the type of the receiver; the type the method belongs to | Order, *Bill |
| Value receiver | a receiver of type T; the method gets a copy |
func (b Bill) Add |
| Pointer receiver | a receiver of type *T; the method sees the original |
func (b *Bill) Add |
| Pointer method | a method with a pointer receiver | Add on *Bill |
| Overloading | several functions sharing a name, chosen by argument types; Go has none | total(o) / total(b) fails |
| Redeclared | a name declared twice in the same scope | total redeclared in this block |
| Automatic address-of | Go rewrites v.M() to (&v).M() for a pointer method on an addressable value |
b.Add() |
| Automatic dereference | Go rewrites p.M() to (*p).M() for a value method, and p.Field to (*p).Field |
p.Total(), b.Items |
| Dereference | go from an address to the value stored there | *p |
| Addressable value | a value you can take the address of with & |
variables, s[i], p.Field |
| Method set | the methods a type has; T: value methods, *T: all |
*Bill has Add and Total |
| Defined type | a new named type made with type Name Underlying |
type Rupees float64 |
| Underlying type | the type a defined type is built from | float64 for Rupees |
| Non-struct defined type | a defined type based on a number, string, slice, map... which can have methods | Rupees, type Orders []Order |
| Local type | a type declared in your own package; may get methods | Rupees, Bill |
| Non-local type | a built-in or other package's type; no new methods allowed | float64, time.Duration |
| Type alias | another name for the same type, keeping its methods | type Alias = Bill |
String() method |
a method String() string that fmt uses to print a value |
Rs 100.00 |
fmt.Stringer |
the interface of types with String() string (episode 21) |
Rupees |
| Interface | a type describing methods a value must have (episode 21) | fmt.Stringer |
| Infinite recursion | a function calling itself with no way to stop | Sprintf("%v", r) inside String |
go vet |
a tool that finds suspicious code | causes recursive ... String method call |
| Zero value | the value a variable has before anything is stored | var b Bill |
| Panic | a run-time error that stops the program, with a trace | panic: assignment to entry in nil map |
| Nil map | a map never created; reads are empty, writes panic | assignment to entry in nil map |
| Constructor function | an ordinary function that builds a ready value | NewBill(4) |
| NewX convention | constructors are named New + type name, return *X |
NewKhata("Asha") |
new(T) |
built-in: allocates a zeroed T, returns *T |
new(Bill) |
| Keyed literal | a struct literal naming its fields | &Bill{Table: 4} |
| Escape analysis | the compiler deciding whether a value outlives its function | &Bill{...} escapes to heap |
| Garbage collector | the part of Go that frees heap memory nobody uses | automatic |
| Heap / stack | memory that lives while referenced / memory freed when a function returns | moved to heap |
| Inlining | the compiler pasting a small function's body into its caller | can inline NewBill |
| Function value | a function stored in a variable or passed as an argument | f func() |
| Method value | a method with its receiver already bound, used as a function value | tap := c.Tap |
| Method expression | Type.Method: a function whose first parameter is the receiver |
(*Counter).Tap |
| Receiver consistency rule | if one method needs *T, give all methods *T |
all *Khata |
| Receiver naming | short, consistent, never this/self |
b for Bill |
| Nil pointer | a pointer that points to nothing | var b *Bill |
| Nil receiver | calling a pointer method on a nil pointer | empty.Len() → 0 |
| Exported / unexported | uppercase names are visible to other packages, lowercase are not | Balance / balance |
| Encapsulation | hiding data in unexported fields, changed only through methods | k.Buy(30) |
| Getter | a method that returns a hidden field; named without Get |
Balance() |
Summary
- Go has no overloading: one function name per package (
total redeclared in this block). Related behaviour becomes methods. - A method is a function with a receiver:
func (o Order) Amount() float64, calledo.Amount(). Different types can each have aTotal. - A value receiver
(b Bill)gets a copy (the0 0bug); a pointer receiver(b *Bill)works on the original. - Go adds
&(automatic address-of) and*(automatic dereference) at calls, but only for addressable values: map elements and literals givecannot call pointer method Add on Bill. - Method sets:
Thas the value-receiver methods,*Thas both. They decide which interfaces a type satisfies. - Any local defined type can have methods (
Rupees.String,WithGST); built-in and other packages' types can't (non-local type float64). A new defined type doesn't inherit methods.String()makesfmtprint your type; convert to the underlying type inside it to avoid recursion. - Constructors are ordinary
NewXfunctions that return a ready*X(fixing the nil-map panic); escape analysis makes returning the pointer safe. - Method values (
c.Tap) bind the receiver when created; method expressions ((*Counter).Tap) take it as the first argument. - Receiver consistency rule: if one method needs a pointer receiver, use pointer receivers for all. Pointer methods can even handle a nil receiver.
- Encapsulation: unexported fields plus methods, like the khata's
balancechanged only byBuyandPay.
Homework from the video: a Temperature type with String(), a Stack with Push, Pop and Len (pointer receivers: they change the slice), a stricter NewKhata, and a method value passed to a function.
Next episode: Interfaces: one printReceipt for every type that has the right methods, implicit satisfaction, any, fmt.Stringer, and nil interfaces.