Composing Types by Struct Embedding

Go+ does not provide the typical, type-driven notion of subclassing, but it does have the ability to “borrow” pieces of an implementation by embedding types within a struct or interface. Only interfaces can be embedded within interfaces.

The Sample has two struct types, Hello struct and Goodbye struct, each of which implements the Talk interface. And HelloGoodbye struct also implements Talk interface, which it does by combining Hello struct and Goodbye struct into one struct using embedding: it lists the types within the struct but does not give them field names.

type Talk interface { Say() } type Hello struct { name string } func (hello *Hello) Say() { println "Hello ", hello.name } func (hello *Hello) Sleep() { println "Hello ", hello.name, "go to bed!" } type Goodbye struct { name string } func (goodbye *Goodbye) Say() { println "Goodbye ", goodbye.name } type Forward struct { } func (forward *Forward) Say() { forward.SayForward() } func (forward *Forward) SayForward() { println "You must forward method!" } type HelloGoodbye struct { *Hello *Goodbye forward *Forward } func (hg *HelloGoodbye) Say() { hg.Hello.Say() hg.Goodbye.Say() hg.forward.Say() } helloGoodbye := HelloGoodbye{ &Hello{"tsingbx"}, &Goodbye{"tsingbx"}, &Forward{}, } helloGoodbye.Say() println() helloGoodbye.Sleep() println() helloGoodbye.forward.SayForward()

The embedded elements are pointers to structs and of course must be initialized to point to valid structs before they can be used.

The HelloGoodbye struct also have forward member written as forward *Forward, but then to promote the methods of the forward and to satisfy the Talk interface, we would also need to provide forwarding methods, like this: hg.forward.Say(). By embedding the structs directly, we avoid this bookkeeping. The methods of embedded types come along for free, which means that HelloGoodbye struct also has the methods of Hello struct and Goodbye struct.

There’s an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one. In our example, when the Sleep method of a HelloGoodbye is invoked, it has exactly the same effect as the forwarding method helloGoodbye.Hello.Sleep(); the receiver is the helloGoodbye.Hello, not the helloGoodbye itself.

Embedding can also be a simple convenience.

This example shows an embedded field alongside a regular, named field.

import "log" import "fmt" import "os" type Job struct { Command string *log.Logger } func (job *Job) Printf(format string, args ...interface{}) { job.Logger.Printf("%q: %s", job.Command, fmt.Sprintf(format, args...)) } func NewJob(command string, logger *log.Logger) *Job { return &Job{command, logger} } job := &Job{"cmd", log.New(os.Stderr, "Job: ", log.Ldate)} job.Println("starting now...") job.Printf("format string %d", 1)

The Job type now has the Print, Printf, Println and other methods of *log.Logger. We could have given the Logger a field name, of course, but it’s not necessary to do so. And now, once initialized, we can log to the Job: job.Println(“starting now…”)

The Logger is a regular field of the Job struct, so we can initialize it in the usual way inside the constructor for Job, like function NewJob do, or with a composite literal, job := &Job{command, log.New(os.Stderr, “Job: “, log.Ldate)}

If we need to refer to an embedded field directly, the type name of the field, ignoring the package qualifier, serves as a field name, as it did in the Printf method of our Job struct. Here, if we needed to access the *log.Logger of a Job variable job, we would write job.Logger, which would be useful if we wanted to refine the methods of Logger.

Embedding types introduces the problem of name conflicts but the rules to resolve them are simple. First, a field or method X hides any other item X in a more deeply nested part of the type. If log.Logger contained a field or method called Command, the Command field of Job would dominate it.

Second, if the same name appears at the same nesting level, it is usually an error; it would be erroneous to embed log.Logger if the Job struct contained another field or method called Logger. However, if the duplicate name is never mentioned in the program outside the type definition, it is OK. This qualification provides some protection against changes made to types embedded from outside; there is no problem if a field is added that conflicts with another field in another subtype if neither field is ever used.

Next example: Method Values and Expressions