×

go · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Embed a type in a struct and its methods come along too.

Write a type inside a struct with no field name, and you are it. type Server struct { Logger; name string } gives every Server a Logger inside. Its fields and methods are : s.Log("hi") works as if Server had its own Log.

It is not inheritance. A Server is not a Logger; it has one, and s.Log is shorthand for s.Logger.Log. If Server defines a Log of its own, that one wins, and the embedded one is still there as s.Logger.Log.

A favourite use is embedding sync.Mutex beside the data it guards, so c.Lock() and c.Unlock() read naturally.

package main
import "fmt"
type Logger struct {
	prefix string
}
func (l Logger) Log(msg string) {
	fmt.Println(l.prefix + msg)
}
type Server struct {
	Logger
	name string
}
func main() {
	s := Server{Logger: Logger{prefix: "[web] "}, name: "shop"}
	s.Log("starting " + s.name)
	s.Logger.Log("the same method, the long way round")
	fmt.Println("prefix is", s.prefix)
}

The embedded field's name is its type's name, so you set it with Logger: Logger{...}.