无法在非接口值上键入开关 [英] 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
推荐答案
类型开关需要一个接口来进行自省.如果您将已知类型的值传递给它,它就会爆炸.如果您创建一个接受接口作为参数的函数,它将起作用:
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")
}
}
在此处查看完整代码 http://play.golang.org/p/QNyf0eG71_ 和 golang 文档接口 http://golang.org/doc/effective_go.html#interfaces.
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.
这篇关于无法在非接口值上键入开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!