无法在非接口值上键入switch [英] 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_ 上查看完整的代码,并在接口 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.
这篇关于无法在非接口值上键入switch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!