Go Structs and Methods
Group fields in a struct and attach behavior to it.
On this page
Go functions.
- Group fields in a struct and attach behavior to it.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
Go has no classes. A struct groups named fields, and a method is a function with a receiver written before its name. func (r Rect) Area() int means Area can be called on any Rect value.
Rect{Width: 3, Height: 4} builds a value with named fields, and r.Area() calls the method. This receiver gets a copy of the value; use a pointer receiver such as *Rect when a method must change the original.
Code example
package main
import "fmt"
type Rect struct {
Width, Height int
}
func (r Rect) Area() int {
return r.Width * r.Height
}
func main() {
r := Rect{Width: 3, Height: 4}
fmt.Println(r.Area())
}12
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
package main import "fmt" type Rect struct { Width, Height int} func (r Rect) Area() int { return r.Width * r.Height} func main() { r := Rect{Width: 3, Height: 4} fmt.Println(r.Area())}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Define a type with two int fields. | — | — | |
| Attach Area to Rect through the receiver r. | — | — | |
| Create a value with named fields. | r = {3 4} | — | |
| The method multiplies the fields: 3 * 4. | return = 12 | 12 |
Behind the scenes
How Go processes this code
The Go compiler builds an executable. Its runtime starts the main function in package main.
Cost and common mistakes
O(1) time and space.
- A value receiver works on a copy, so assigning to its fields does not change the caller's value.
- Names that start with a lowercase letter are private to the package.
Try it yourself
Add a Perimeter method.
Reveal answer and reasoning
func (r Rect) Perimeter() int { return 2 * (r.Width + r.Height) } returns 14 for this rectangle.