Methods on Structs
A method is a function that's "attached" to a type. The only difference from a regular function is the receiver — a special parameter written before the method name:
type Persegi struct {
Sisi float64
}
func (p Persegi) Luas() float64 {
return p.Sisi * p.Sisi
}
func (p Persegi) Keliling() float64 {
return 4 * p.Sisi
}
Here Persegi is a square with a side length (Sisi), and the methods compute its area (Luas) and perimeter (Keliling).
You call a method with a dot, just like accessing a field:
kotak := Persegi{Sisi: 3}
fmt.Println(kotak.Luas()) // 9
fmt.Println(kotak.Keliling()) // 12
The receiver name is usually short — one or two letters from the type name (p for Persegi).
Value receivers work on a copy
The receiver (p Persegi) is called a value receiver: the method gets a copy of the struct. Changing a field inside the method doesn't affect the original struct:
func (p Persegi) Perbesar() {
p.Sisi = p.Sisi * 2 // hanya mengubah salinan!
}
kotak.Perbesar()
fmt.Println(kotak.Sisi) // tetap 3
Perbesar ("enlarge") only changes the copy, so kotak.Sisi is still 3.
With a value receiver, the way to "change" something is to return a new value:
func (p Persegi) Diperbesar() Persegi {
p.Sisi = p.Sisi * 2
return p
}
besar := kotak.Diperbesar() // besar.Sisi == 6, kotak.Sisi tetap 3
(Methods that really change the original struct use a pointer receiver, covered in the Pointers chapter.)
Methods and the zero value
You can still call a method on a struct's zero value. Good design makes sure the zero value still produces something sensible:
var p Persegi
fmt.Println(p.Luas()) // 0
Task
The "Senja" coffee shop records orders with the Pesanan (order) type. Complete three methods (all with value receivers):
-
(p Pesanan) Total() int— the subtotal isHarga * Jumlah(price times quantity). IfMemberistrue, apply a 10% discount:subtotal * 90 / 100. -
(p Pesanan) Struk() string— a receipt line in this format:<Jumlah>x <Menu> = Rp<Total>Example:
2x Latte = Rp44000(use the result of theTotalmethod). -
(p Pesanan) TambahJumlah(n int) Pesanan— return a new order withJumlahincreased byn. The original order must not change.