Structs and methods in Go
Composite types, embedding, and receivers.
type Address struct {
City string
Country string
}
type User struct {
Name string
Age int
Address
}
func (u User) Label() string {
return u.Name + " of " + u.City
}
func (u *User) Birthday() {
u.Age++
}
How it works
- Embedding
Addresspromotes its fields. - A value receiver reads; a pointer receiver mutates.
- Methods attach behavior without classes.
Keywords and builtins used here
funcintreturnstringstructtype
The run, in numbers
- Lines
- 18
- Characters to type
- 209
- Tokens
- 55
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 35 seconds.
Step 1 of 3 in Structs & methods, step 1 of 19 in Interfaces & generics.