Interfaces
Learn about interfaces in Go.
Checking if an interface variable is nil
This is certainly one of the most common traps in Go. An interface in Go is not simply a pointer to a memory location as in some other languages.
An interface has:
- A static type (the type of the interface itself)
- A dynamic type
- A value
Note: A variable of an interface type is equal to nil when both its dynamic type and value are nil.”
Press + to interact
package mainimport ("fmt")type ISayHi interface {Say()}type SayHi struct{}func (s *SayHi) Say() {fmt.Println("Hi!")}func main() {// at this point variable “sayer” only has the static type of ISayHi// dynamic type and value are nilvar sayer ISayHi// as expected sayer equals to nilfmt.Println(sayer == nil) // true// a nil variable of a concrete typevar sayerImplementation *SayHi// dynamic type of the interface variable is now SayHi// the actual value interface points to is still nilsayer = sayerImplementation// sayer no longer equals to nil, because its dynamic type is set// even though the value it points to is nil// which isn't what most people would expect herefmt.Println(sayer == nil) // false}
The interface value is set to a nil struct
. The interface can’t be used
for ...
Get hands-on with 1400+ tech skills courses.