In my tenure of writing Go code, I have never encountered a case, nor can I think of one that would require using a pointer to an interface, except for perhaps writing a library that makes heavy use of runtime reflection. Some people allude to the fact that there are valid reasons for doing so, but seem to never elaborate further. This feature also seems to cause quite a bit of confusion with developers who are getting started with Go.
main.go:22: cannot use &a (type *A) as type **interface {} in argument to run
What would be a good example of using an interface pointer?
A special case in the language specification is required to disallow pointers to interfaces. That makes the language more complex.
Creating a reflect.Type
for an interface interface type is one scenario where pointers to interfaces come in handy: reflect.TypeOf((*io.Closer)(nil)).Elem()
is the reflect type of io.Closer
.
Only example I can come up with, but never used nor seen in the wild, is to let another function populate your interface.
Example on Play. I can't really imagine a case where it is needed. As others have pointed out, not allowing it would probably be wrong as that would make the compiler more complicated.
package main
import "fmt"
func main() {
var s fmt.Stringer
setMyStringer(&s)
fmt.Println("Hello, stringer:", s)
}
func setMyStringer(target *fmt.Stringer) {
*target = Stringable(5)
}
type Stringable int
func (s Stringable) String() string {
return fmt.Sprint(int(s))
}