【问题标题】:Checking for "struct" type in a type switch statement in Go results in syntax error在 Go 中的类型 switch 语句中检查“struct”类型会导致语法错误
【发布时间】: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 完整代码:

https://play.golang.org/p/F820vMJRum

【问题讨论】:

    标签: go struct


    【解决方案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 上试试。

    【讨论】:

    • 感谢@icza 的解释那么,我可以说struct 关键字用于创建一个类型(例如struct {i int},如您的示例),但它本身不是一个类型?
    • @Agrim struct 这个词本身不是一个类型,它只是一个关键字,但struct { i int } 是一个type literal,它一个类型。
    猜你喜欢
    • 2023-03-10
    • 2022-08-17
    • 2017-03-19
    • 2020-05-17
    • 2017-01-05
    • 2014-11-01
    • 2012-05-26
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多