2

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?

Community
  • 1
  • 1
N J
  • 123
  • 5
  • 2
    You're just looking at it wrong. Why should you not allow it? Without a compelling reason not to (which there isn't as far as I'm concerned), there's no reason to explicitly not allow it. – evanmcdonnal Apr 04 '16 at 23:44
  • 3
    Didn't see any confusion about that topic. I read many articles about people learning Go and pointing some weird or bad stuff about it but never pointers to interfaces. It's something that is pretty much not needed in practice so you shouldn't even think about. Restricting it - it would make the language more complex without any obvious benefits. It's possible, comes naturally out of specification so why restricting it. I don't even remember seeing this feature in any of Go tutorials or books. – creker Apr 05 '16 at 00:21
  • 1
    Related / example: [Set an interface to nil in Golang](http://stackoverflow.com/questions/33841630/set-an-interface-to-nil-in-golang) – icza Apr 05 '16 at 06:13
  • It's totally legitimate for a Go program to implement an interface on a nil pointer. – Jon Watte Nov 28 '18 at 20:41

2 Answers2

4

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.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
1

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))
}
David Budworth
  • 11,248
  • 1
  • 36
  • 45