GoGo
IntermediateLesson 7 of 15

Structs, Methods & Pointers – Go

The Go way to "objects": data in structs, behavior in methods.

Go has no classes. Instead you bundle data in a struct and attach methods via a receiver: func (k *Konto) Einzahlen(...). Constructors are ordinary functions, usually NewXyz. If a type has a method String() string, fmt uses it automatically when printing.

package main

import "fmt"

type Konto struct {
	Inhaber string
	Saldo   float64
}

func NewKonto(inhaber string) *Konto {
	return &Konto{Inhaber: inhaber}
}

func (k *Konto) Einzahlen(betrag float64) {
	k.Saldo += betrag
}

func (k *Konto) String() string {
	return fmt.Sprintf("%s: %.2f", k.Inhaber, k.Saldo)
}

func main() {
	k := NewKonto("Ada")
	k.Einzahlen(50)
	k.Einzahlen(25.5)
	fmt.Println(k) // Ada: 75.50
}

Go always passes arguments as a copy. If you want to modify the original (or avoid copying large structs), you pass a pointer (*T). &x yields the address, *p the value behind it. Methods with a pointer receiver may modify the object.

package main

import "fmt"

func verdoppleWert(n int)    { n *= 2 }
func verdoppleZeiger(n *int) { *n *= 2 }

func main() {
	x := 10
	verdoppleWert(x)
	fmt.Println(x) // 10 (only the copy was doubled)
	verdoppleZeiger(&x)
	fmt.Println(x) // 20

	p := &x
	*p = 5
	fmt.Println(x, *p) // 5 5
}

Instead of inheritance there is embedding (composition): an embedded type "lends" its fields and methods to the outer type, which may override them if needed.

package main

import "fmt"

type Tier struct{ Name string }

func (t Tier) Sprich() string { return t.Name + " makes a sound" }

type Hund struct {
	Tier // embedded
	Rasse string
}

func (h Hund) Sprich() string { return h.Name + " says Woof!" }

func main() {
	h := Hund{Tier{"Rex"}, "Dackel"}
	fmt.Println(h.Sprich())      // Rex says Woof!
	fmt.Println(h.Tier.Sprich()) // Rex makes a sound
	fmt.Println(h.Name)          // Rex – field of Tier
}
WarningDo not mix value and pointer receivers at random: if a method changes state, you need *T – otherwise you only change a copy. Calling it through a variable still works (k.Einzahlen(5)), because Go automatically takes &k.
TipExported fields begin with an uppercase letter (Name). Only such fields are visible to encoding/json and other packages.