How to get correct underlying type of interface

I’m trying to find out what type was passed into an interface. The interface is implemented by two struct types.

type T interface {
	hello()
}

type foo struct{}

func (f *foo) hello() {}

type boo struct{}

func (b *boo) hello() {}

func main() {
	abc(&foo{})
	abc(&boo{})
}

func abc(t T) {
	switch t {
	case &foo{}:
		fmt.Println("foo")

	case &boo{}:
		fmt.Println("boo")

	default:
		fmt.Println("NOTHING")
	}
}

This always prints out "NOTHING" and "NOTHING"
Could someone please clarify what I’m missing?
Link to full code: Go Playground - The Go Programming Language

Trying with type assertion:

func abc(t T) {
	switch t.(type) {
	case foo{}:
		fmt.Println("foo")

	case boo{}:
		fmt.Println("boo")

	default:
		fmt.Println("NOTHING")
	}
}

I get a compile time error:
Impossible type switch case: 'foo' does not implement 'T' and
Impossible type switch case: 'boo' does not implement 'T'

foo{} is a value, you want a type, specifically *foo in your case.

1 Like

Thanks a lot

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.