Go · Course navigation

Go Structs and Methods

Group fields in a struct and attach behavior to it.

On this page
Before you start

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

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

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1package main
2
3import "fmt"
4
5type Rect struct {
6 Width, Height int
7}
8
9func (r Rect) Area() int {
10 return r.Width * r.Height
11}
12
13func 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading