在了解Go中的type switch语句时,我尝试按如下方式检查“struct”类型:
2.txt
但是,这导致了与0.txt --> 000.txt
4.txt --> 004.txt
25.txt --> 025.txt
180.txt --> 180.txt
类型相关的语法错误(如果删除了检查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)
}
类型的case语句,则无法看到:
struct
有没有理由不能在这里检查struct
类型?请注意,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
的{{1}},这是一个应该由每种类型实现的空接口,包括func moo()
Go Playground完整代码:
答案 0 :(得分:1)
struct
不是类型,而是keyword。
这是一种类型(使用type literal给出):
struct { i int }
或Point
:
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")
}
在Go Playground上尝试。