Putting one struct inside another

An express order is an order with one extra value: how many minutes the delivery may take. You could copy all of Order's fields into a new struct, but then you would also have to copy its methods. Go has a shorter way. Inside a struct, you can write another struct's type name with no field name in front. This is called embedding.

package main

import "fmt"

type Order struct {
	ID       int
	Customer string
}

func (o Order) Label() string {
	return fmt.Sprintf("#%d %s", o.ID, o.Customer)
}

type ExpressOrder struct {
	Order
	Minutes int
}

func main() {
	e := ExpressOrder{
		Order:   Order{ID: 101, Customer: "Alice"},
		Minutes: 20,
	}
	fmt.Println(e.ID, e.Customer, e.Minutes)
	fmt.Println(e.Label())
	fmt.Printf("%+v\n", e)
}

Output:

101 Alice 20
#101 Alice
{Order:{ID:101 Customer:Alice} Minutes:20}

The line Order inside ExpressOrder embeds an Order. The fields and methods of the inner Order are promoted: you can use them on the outer value as if they were its own. So e.ID works, and so does e.Label().

The %+v line shows what is really inside. An ExpressOrder has a field called Order (named after its type) and a field called Minutes. e.ID is a short way to write e.Order.ID, and the long form works too.

If ExpressOrder had its own field called Customer, then e.Customer would mean the outer field. You could still reach the inner one with e.Order.Customer.

Building the value

The promoted names work for reading and writing fields, but not inside a struct literal. There you must build the inner Order yourself, as the program above does. Using ID directly is an error:

package main

import "fmt"

type Order struct {
	ID       int
	Customer string
}

type ExpressOrder struct {
	Order
	Minutes int
}

func main() {
	e := ExpressOrder{ID: 101, Minutes: 20}
	fmt.Println(e)
}

Output:

# command-line-arguments
./main.go:16:20: unknown field ID in struct literal of type ExpressOrder

Embedding is not inheritance

Some languages have inheritance, where a new type can be used anywhere an older type is expected. Go has no inheritance. An ExpressOrder contains an Order, but it is not an Order. A function that takes an Order does not accept an ExpressOrder:

package main

import "fmt"

type Order struct {
	ID       int
	Customer string
}

type ExpressOrder struct {
	Order
	Minutes int
}

func show(o Order) {
	fmt.Println(o.ID, o.Customer)
}

func main() {
	e := ExpressOrder{
		Order:   Order{ID: 101, Customer: "Alice"},
		Minutes: 20,
	}
	show(e)
}

Output:

# command-line-arguments
./main.go:24:7: cannot use e (variable of type ExpressOrder) as Order value in argument to show

To pass the inner order, write show(e.Order). When you need one function that works with several different types, Go uses interfaces, which come in the Interfaces lesson.

In the exercise, embed Order in ExpressOrder and build an express order from the input.