Go — Structs and value receivers
A Go struct groups named fields. A method with a value receiver can read a line item’s quantity and unit price and return its subtotal.
A simple example
Read one field
- Start with A point with x = 2
- Do this Read x
- Result 2
package main
import "fmt"
func main() {
type Point struct { X int }
point := Point{X: 2}
fmt.Println(point.X)
}
2
Represent an invoice line
The receiver before Subtotal associates the method with LineItem. A value receiver receives a copy. The keyed struct literal shows which field holds cents per unit.
A café invoice lists three juices at 125 cents each. Store the quantity and price together, then calculate the subtotal when the receipt is printed. Changing the quantity can then update the total automatically.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
type LineItem struct {
Units int
Cents int
}
func (line LineItem) Subtotal() int {
return line.Units * line.Cents
}
func main() {
line := LineItem{Units: 3, Cents: 125}
fmt.Println(line.Subtotal())
}
375
The line holds three units at 125 cents each. Multiplication gives 375 cents. Keeping the subtotal derived means there is no third field that can become stale.
Try it yourself
Create a second line with two units at 90 cents each.
Check your answer
Its subtotal is 180 cents. The two subtotals together are 555 cents before any taxes or delivery charges.