检查“是否存在”;结构";在Go中键入类型开关语句会导致语法错误
在学习Go中的type switch语句时,我尝试检查“struct”类型,如下所示:检查“是否存在”;结构";在Go中键入类型开关语句会导致语法错误,go,struct,Go,Struct,在学习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 %
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()
正在检查interface{}
类型的i
,这是一个空接口,应该由每种类型实现,包括struct
转到游戏场完整代码:
struct
不是一个类型,而是一个
这是一种类型,例如(使用a给出):
或点
:
type Point struct { X, Y int }
因此,以下代码起作用:
switch v := i.(type) {
case struct{ i int }:
fmt.Printf("Life is complicated with %v \n", v)
case Point:
fmt.Printf("Point, X = %d, Y = %d \n", v.X, v.Y)
}
您可以将struct
视为一种类型,可以使用反射进行检查,例如:
var p Point
if reflect.TypeOf(p).Kind() == reflect.Struct {
fmt.Println("It's a struct")
}
请在上尝试。谢谢@icza的解释,那么,我可以说
struct
关键字用于创建一个类型(例如,struct{I int}
),但它本身不是一个类型吗?@Agrimstruct
单词本身不是一个类型,它只是一个关键字,但struct{I int}
是一种,它是一种类型。
var p Point
if reflect.TypeOf(p).Kind() == reflect.Struct {
fmt.Println("It's a struct")
}