wzzzz
wzzzz

Reputation: 49

Behaviour of nil receiver in method in Golang

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().

Upvotes: 4

Views: 1838

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51592

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.

Upvotes: 9

Related Questions