Thomas Geulen
Thomas Geulen

Reputation: 610

reflect value Interface and pointer receiver

In the mongodb driver for golang there is the following piece of code:

case reflect.Struct:
    if z, ok := v.Interface().(Zeroer); ok {
        return z.IsZero()
    }
    return false

Interface Zeroer is defined like this:

type Zeroer interface {
    IsZero() bool
}

When I implement my struct with

func (id SomeStruct) IsZero() bool {
    return id.ID == ""
}

it works. But when I implement the IsZero method with a pointer receiver:

func (id *SomeStruct) IsZero() bool {
        return id.ID == ""
 }

the type assertion fails and IsZero does not get executed.

Can someone explain this to me?

Upvotes: 2

Views: 1469

Answers (1)

Zak
Zak

Reputation: 5898

Presumably somewhere above the case reflect.Struct there is a switch on reflect.ValueOf(...).Kind()

If you look at the Kinds in the reflect package, docs here

Struct is one of the kinds and Ptr is another. In the switch statement it is not matching because the kind *SomeStruct as defined in the receiver of the IsZero() method is Ptr and not Struct.

You'd need to do v.Elem().Interface().(Zeroer) to get the underlying element

Runnable example here https://play.golang.org/p/tx1zgD7Ri0E

Upvotes: 1

Related Questions