Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot type switch on non-interface value

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

like image 447
Mingyu Avatar asked Apr 19 '14 15:04

Mingyu


1 Answers

I figured out the answer, which is to cast n to interface{} before the type assertion:

switch v := interface{}(n).(type) 
like image 132
Mingyu Avatar answered Oct 11 '22 13:10

Mingyu