4 ms·
How does nil implement an interface?
by waheoo 6y ago
How does nil implement an interface?
- eptcyka 6y agoA pointer to a type that implements an interface can be nil, but a function that takes said pointer as an interface type will not be able to distinguish between a pointer that points to an allocated object and a nil one.
- siebenmann 6y agoAttempting to call a method on a nil interface value produces a runtime panic. Otherwise, it is the type that implements an interface, and it's possible that the type works even if the specific value of the type is nil. For instance, you could have a 'myIntPointer' type that is a pointer to an int, and implement a String() method for myIntPointer, and at that point a nil myIntPointer still has a String() method and implements the fmt.Stringer interface (although it may get a runtime panic if you actually call the method).