typestar

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

  1. Embedding Address promotes its fields.
  2. A value receiver reads; a pointer receiver mutates.
  3. Methods attach behavior without classes.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Structs & methods, step 1 of 19 in Interfaces & generics.

Next →