Sikau

Go · Day 4 · about 40 min

Structs and methods

Struct types, value vs pointer receivers, embedding.

Objects without classes

Go has no classes and no inheritance. Instead it has structs — named collections of fields — and methods you can attach to any type you define. Instead of inheritance it offers embedding: put one struct inside another and its fields and methods are promoted. That's the whole object model, and it's enough for Docker and Kubernetes.

The one decision you'll make again and again is the receiver: does a method get a copy of the value, or a pointer to it? Get it wrong and your method changes a copy that's thrown away — mistake #42, and a bug you can spot in seconds once you've seen it.

Structs

A struct groups fields: type Point struct { X, Y int }. Create one with a composite literal — Point{1, 2} or, clearer, Point{X: 1, Y: 2}; fields you leave out get their zero values. Structs are values: assigning or passing one copies every field. To share one, use a pointer, &Point{…}, and Go lets you write p.X whether p is a struct or a pointer to one.

package main

import "fmt"

type Student struct {
	Name  string
	Grade int
}

func main() {
	a := Student{Name: "Asha", Grade: 9}
	b := a
	b.Grade = 10
	p := &a
	p.Grade = 11
	fmt.Println(a, b)
	fmt.Printf("%+v\n", a)
}

The rest of this lesson

  • Methods and receiversexplain
  • Embeddingexplain
  • Copy or not?predict
  • Pick the receivermatch
  • A constructorfill
  • A small bankwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Go