Structs, methods and interfaces

Your own types with structs, behaviour with methods and pointers, and flexible code with interfaces.

About 4 hours of study

Learning objectives

Lessons

  1. 1

    Structs

    Grouping related values into your own type with struct: declaring, creating with named fields, reading and changing fields, nesting, slices of structs, comparing and printing structs.

  2. 2

    Methods and pointers Intermediate

    Adding methods to your types, pointers with & and *, value and pointer receivers, why a method must use a pointer to change its value, constructors and the String method.

  3. 3

    Interfaces Intermediate

    Describing behaviour with interfaces: implicit implementation, using an interface as a parameter or slice element, type assertions and type switches, the empty interface, and sort.Interface.

Module practice

Module quiz

1. Which line creates a Person value with named fields?
2. Which kind of receiver lets a method change the struct it is called on?
3. How does a type satisfy an interface in Go?
4. What does *p do when p is a pointer?
5. What does q := p do when p is a struct value?
6. What does a type switch do?

‹ Slices, maps and stringsErrors, goroutines and a complete program ›