Cannot type switch on non-interface value

前端 未结 4 2066
说谎
说谎 2021-02-04 01:01

I am playing with type assertion using the following dummy code, and I got the error:

cannot type switch on non-interface value

Doe

4条回答
  •  感情败类
    2021-02-04 01:07

    Type switches require an interface to introspect. If you are passing a value of known type to it it bombs out. If you make a function that accepts an interface as a parameter, it will work:

    func typeSwitch(tst interface{}) {
        switch v := tst.(type) {
            case Stringer:
               fmt.Println("Stringer:", v)
            default:
               fmt.Println("Unknown")
        }
    }
    

    See the full code here http://play.golang.org/p/QNyf0eG71_ and the golang documentation on interfaces http://golang.org/doc/effective_go.html#interfaces.

提交回复
热议问题