package main
import (
"fmt"
)
type I interface {
M()
}
type T struct {
}
func (t *T) M() {
fmt.Println(t == nil)
}
func main() {
var i I
var t *T
i = t
fmt.Println(i == nil)
i.M()
}
The result is false and true.
The value in both cases is nil and type is *main.T.
I understand that in the first case i == nil is false because the variable i does not have a nil type.
I do not understand why t == nil is true inside the method M().
In the first case, i==nil is false, because i is an interface whose type is T and whose value is nil. For an interface to be equal to the literal value nil, it has to have both type and value nil. Here, i has non-nil type.
In the second case, the receiver is simply nil, because the receiver of the function M is a value of type *T whose value is nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With