From f00be0caeec654587270c558bcc1b322f7251450 Mon Sep 17 00:00:00 2001
From: Rob Pike io.ReadWriter
.
-There's one important way in which embedding differs from subclassing. When we embed a type,
+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 Read
method of a bufio.ReadWriter
is
-invoked, it has the exactly the same effect as the forwarding method written out above;
+invoked, it has exactly the same effect as the forwarding method written out above;
the receiver is the reader
field of the ReadWriter
, not the
ReadWriter
itself.
+Embedding can also be a simple convenience. +This example shows an embedded field alongside a regular, named field. +
++type Job struct { + Command string; + *log.Logger; +} ++
+The Job
type now has the Log
, Logf
+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 we can
+log to a Job
:
+
+job.Log("starting now..."); ++
+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. If we needed to access the
+*log.Logger
of a Job
variable job
,
+we would write job.Logger
.
+This would be useful if we wanted to refine the methods of Logger
.
+
+func (job *Job) Logf(format string, v ...) { + job.Logger.Logf(fmt.Sprintf("%q: %s", job.command, format), v); +} ++
+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 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 that field
+is never used.
+