Go from zero: a struct is the object
A struct groups named fields, and a method is a function on that struct. Item holds a drink and a price in cents, and Label prints latte $4.50.
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.
One value is often too small. A drink has a name and a price. A struct is the object that holds both. A method is a function that belongs to that struct, so the fields are already in reach. Label is the line you would put on a cup.
The object is the fields plus the method#
A struct is one value made of named fields. Item is not a class you instantiate with new. It is a layout: a string, then an int. The method is a function with that layout as its receiver, so Label can read Name and Cents without taking them as extra arguments. The picture shows the fields going in and the string the method hands back. Cents stay a whole number of cents so the price never becomes a binary fraction. The method is where those cents become $4.50.
- Namestringlatte
- Centsint450
- Label()stringlatte $4.50
package main
import "fmt"
type Item struct {
Name string
Cents int
}
func (it Item) Label() string {
return fmt.Sprintf("%s $%d.%02d", it.Name, it.Cents/100, it.Cents%100)
}
func main() {
latte := Item{Name: "latte", Cents: 450}
fmt.Println(latte.Label())
}
latte $4.50
Fields, then a method#
Item has two fields. Name is a string. Cents is an int, and the unit is cents so the price stays a whole number. latte := Item{Name: "latte", Cents: 450} fills both fields by name. You can read them with latte.Name and latte.Cents.
func (it Item) Label() string is a method. The (it Item) says Label is called on an Item, and inside the method that item is named it. latte.Label() is the call. fmt.Sprintf builds the text latte $4.50 and Println writes it. Sprintf returns the string. It does not print on its own.
Why the price is an int of cents#
450 cents is $4.50 when a person reads it. The program keeps 450 so it never has to store the fraction. Adding cents is integer addition. Label divides by 100 only at the edge, when it shows the price. The next lesson looks at the value a field has before you set it.
Your product here? Partner with us
Back to topDiscussion
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.