I am playing with type assertion using the following dummy code, and I got the error:
cannot type switch on non-interface value
Does anyone know what does that mean?
package main import "fmt" import "strconv" type Stringer interface { String() string } type Number struct { v int } func (number *Number) String() string { return strconv.Itoa(number.v) } func main() { n := &Number{1} switch v := n.(type) { case Stringer: fmt.Println("Stringer:", v) default: fmt.Println("Unknown") } }
http://play.golang.org/p/Ti4FG0m1mc
I figured out the answer, which is to cast n
to interface{}
before the type assertion:
switch v := interface{}(n).(type)
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