Structs & Interfaces

Go's approach to object-oriented programming with structs and interfaces.

Structs

Go uses structs instead of classes:

type Person struct {
    Name      string
    BirthYear int
}

func (p Person) Age() int {
    return time.Now().Year() - p.BirthYear
}

func NewPerson(name string, birthYear int) *Person {
    return &Person{Name: name, BirthYear: birthYear}
}
p := Person{Name: "Ada", BirthYear: 1985}
fmt.Println(p.Age())

Pointer receivers

Use pointer receivers when you need to modify the receiver or avoid copying:

func (p *Person) SetName(name string) {
    p.Name = name
}

Embedding (composition over inheritance)

Go has no inheritance — use embedding:

type Employee struct {
    Person      // embed Person
    Company string
}
e := Employee{Person: Person{Name: "Ada"}, Company: "Acme"}
fmt.Println(e.Name)    // "Ada" — promoted field
fmt.Println(e.Age())    // works — promoted method

Interfaces

Interfaces are satisfied implicitly (no implements keyword):

type Describer interface {
    Describe() string
}

func (p Person) Describe() string {
    return fmt.Sprintf("%s (born %d)", p.Name, p.BirthYear)
}

Any type with a Describe() string method satisfies Describer.

Empty interface

var v interface{} = "anything"

Type assertion

s, ok := v.(string)
if ok {
    fmt.Println(s)
}

Common interfaces

Next: Back to Go overview