From: Rob Pike Date: Fri, 15 Mar 2013 18:38:50 +0000 (-0700) Subject: doc/go_faq.html: add entry about pointer to interface X-Git-Tag: go1.1rc2~481 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=09cd13c51dabd709e79329a9b8591fc4d15b6f3f;p=gostls13.git doc/go_faq.html: add entry about pointer to interface R=golang-dev, bradfitz CC=golang-dev https://golang.org/cl/7546050 --- diff --git a/doc/go_faq.html b/doc/go_faq.html index 4c5ead8c59..fab1702a21 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -974,6 +974,57 @@ struct. If the interface value holds a pointer, copying the interface value makes a copy of the pointer, but again not the data it points to.

+

+When should I use a pointer to an interface?

+ +

+Almost never. Pointers to interface values arise only in rare, tricky situations involving +disguising an interface value's type for delayed evaluation. +

+ +

+It is however a common mistake to pass a pointer to an interface value +to a function expecting an interface. The compiler will complain about this +error but the situation can still be confusing, because sometimes a +pointer +is necessary to satisfy an interface. +The insight is that although a pointer to a concrete type can satisfy +an interface, with one exception a pointer to an interface can never satisfy a interface. +

+ +

+Consider the variable declaration, +

+ +
+var w io.Writer
+
+ +

+The printing function fmt.Fprintf takes as its first argument +a value that satisfies io.Writer—something that implements +the canonical Write method. Thus we can write +

+ +
+fmt.Fprintf(w, "hello, world\n")
+
+ +

+If however we pass the address of w, the program will not compile. +

+ +
+fmt.Fprintf(&w, "hello, world\n") // Compile-time error.
+
+ +

+The one exception is that any value, even a pointer to an interface, can be assigned to +a variable of empty interface type (interface{}). +Even so, it's almost certainly a mistake if the value is a pointer to an interface; +the result can be confusing. +

+

Should I define methods on values or pointers?