vendredi 23 juillet 2021

Why doesn't reflect.Type{}.Implements(reflect.TypeOf(Interface(nil))) work?

The title is a little hard to parse so here's more verbose, understandable example:

import "fmt"
import "reflect"

type Stringer interface {
    String() string
}

type MyInt int

func (m MyInt) String() string {
    return fmt.Sprintf("I'm number %d!", m)
}

func main() {
    var m = MyInt(10)
    m_type := reflect.TypeOf(m)

    m_type.Implements(reflect.TypeOf(Stringer(nil))) // This does not work.
}

If you try this code, you will get a panic from within reflect.[some internal class].Implements. Why doesn't this work? Is this some weird side effect of typed nil and nil interfaces?

What's the best workaround for it? I've seen this in the wild:

m_type.Implements(reflect.TypeOf((*Stringer)(nil).Elem())) // true

It works, but it's ugly as hell. Is there a cleaner way? Why does this work when the naive approach does not?





Aucun commentaire:

Enregistrer un commentaire