diff options
author | Shenghou Ma <minux.ma@gmail.com> | 2014-04-17 01:40:04 -0400 |
---|---|---|
committer | Shenghou Ma <minux.ma@gmail.com> | 2014-04-17 01:40:04 -0400 |
commit | f8f34c330c651b16ef8c54e60f4862b4a66b4a41 (patch) | |
tree | 6285f704c1be39b5caeba6c7e182ca9d2a256dd3 | |
parent | 827aab07b80cd8ad26548a6fa234b7d038537d33 (diff) | |
download | go-f8f34c330c651b16ef8c54e60f4862b4a66b4a41.tar.gz go-f8f34c330c651b16ef8c54e60f4862b4a66b4a41.zip |
doc/effective_go: mention that b.Write is a shorthand for (&b).Write when b is addressable.
The rewrite is due to Rob.
LGTM=r, bradfitz, josharian
R=golang-codereviews, bradfitz, r, josharian
CC=golang-codereviews
https://golang.org/cl/87410043
-rw-r--r-- | doc/effective_go.html | 18 |
1 files changed, 15 insertions, 3 deletions
diff --git a/doc/effective_go.html b/doc/effective_go.html index ae04899e19..c522b9ffb7 100644 --- a/doc/effective_go.html +++ b/doc/effective_go.html @@ -2056,10 +2056,22 @@ We pass the address of a <code>ByteSlice</code> because only <code>*ByteSlice</code> satisfies <code>io.Writer</code>. The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be -invoked on pointers. This is because pointer methods can modify the -receiver; invoking them on a copy of the value would cause those -modifications to be discarded. +invoked on pointers. </p> + +<p> +This rule arises because pointer methods can modify the receiver; invoking +them on a value would cause the method to receive a copy of the value, so +any modifications would be discarded. +The language therefore disallows this mistake. +There is a handy exception, though. When the value is addressable, the +language takes care of the common case of invoking a pointer method on a +value by inserting the address operator automatically. +In our example, the variable <code>b</code> is addressable, so we can call +its <code>Write</code> method with just <code>b.Write</code>. The compiler +will rewrite that to <code>(&b).Write</code> for us. +</p> + <p> By the way, the idea of using <code>Write</code> on a slice of bytes is central to the implementation of <code>bytes.Buffer</code>. |