From 49a35a632e1bc6b66d17efc520fdaa2c1543431c Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Fri, 15 Jan 2010 11:59:53 +1100 Subject: [PATCH] be more explicit about initialization of embedded fields. R=rsc CC=golang-dev https://golang.org/cl/186161 --- doc/effective_go.html | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/doc/effective_go.html b/doc/effective_go.html index ab9e3a8c3d..ba36a43fe2 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -1395,7 +1395,7 @@ func (b ByteSize) String() string {

The expression YB prints as 1.00YB, -while ByteSize(1e13) prints as 9.09TB, +while ByteSize(1e13) prints as 9.09TB.

Variables

@@ -1878,12 +1878,15 @@ but does not give them field names. // ReadWriter stores pointers to a Reader and a Writer. // It implements io.ReadWriter. type ReadWriter struct { - *Reader - *Writer + *Reader // *bufio.Reader + *Writer // *bufio.Writer }

-This struct could be written as +The embedded elements are pointers to structs and of course +must be initialized to point to valid structs before they +can be used. +The ReadWriter struct could be written as

 type ReadWriter struct {
@@ -1933,15 +1936,16 @@ type Job struct {
 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:
+a field name, of course, but it's not necessary to do so.  And now, once
+initialized, we can
+log to the Job:
 

 job.Log("starting now...")
 

The Logger is a regular field of the struct and we can initialize -it in the usual way. +it in the usual way with a constructor,

 func NewJob(command string, logger *log.Logger) *Job {
@@ -1949,6 +1953,12 @@ func NewJob(command string, logger *log.Logger) *Job {
 }
 

+or with a composite literal, +

+
+job := &Job{command, log.New(os.Stderr, nil, "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. If we needed to access the *log.Logger of a Job variable job,