Go Structs and Methods
Group fields in a struct and attach behavior to it.
Go
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())
}Output
12
Explanation
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.
Explore the dry run
Guided walkthroughReady
1
package main2
3
import "fmt"4
5
type Rect struct {6
Width, Height int7
}8
9
func (r Rect) Area() int {10
return r.Width * r.Height11
}12
13
func main() {14
r := Rect{Width: 3, Height: 4}15
fmt.Println(r.Area())16
}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 |
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.