【发布时间】:2017-02-28 08:12:55
【问题描述】:
在学习 Go 中的 type switch 语句时,我尝试检查“struct”类型,如下所示:
package main
import "fmt"
func moo(i interface{}) {
switch v := i.(type) {
case string:
fmt.Printf("Byte length of %T: %v \n", v, len(v))
case int:
fmt.Printf("Two times this %T: %v \n", v, v)
case bool:
fmt.Printf("Truthy guy is %v \n", v)
case struct:
fmt.Printf("Life is complicated with %v \n", v)
default:
fmt.Println("don't know")
}
}
func main() {
moo(21)
moo("hello")
moo(true)
}
但是,这导致了与 struct 类型相关的语法错误(如果删除了检查 struct 类型的 case 语句,则看不到:
tmp/sandbox396439025/main.go:13: syntax error: unexpected :, expecting {
tmp/sandbox396439025/main.go:14: syntax error: unexpected (, expecting semicolon, newline, or }
tmp/sandbox396439025/main.go:17: syntax error: unexpected semicolon or newline, expecting :
tmp/sandbox396439025/main.go:20: syntax error: unexpected main, expecting (
tmp/sandbox396439025/main.go:21: syntax error: unexpected moo
这里不能检查struct 类型有什么原因吗?请注意,func moo() 正在检查 i 类型的 interface{},这是一个空接口,应该由每种类型实现,包括 struct
Go Playground 完整代码:
【问题讨论】: