dongxi2163 2017-02-28 08:12
浏览 38
已采纳

在Go中检查类型切换语句中的“ struct”类型会导致语法错误

While learning about the type switch statement in Go, I tried to check for the "struct" type as follows:

package main

import "fmt"

func moo(i interface{}) {
    switch v := i.(type) {
    case string:
        fmt.Printf("Byte length of %T: %v 
", v, len(v))
    case int:
        fmt.Printf("Two times this %T: %v 
", v, v)
    case bool:
        fmt.Printf("Truthy guy is %v 
", v)
    case struct:
        fmt.Printf("Life is complicated with %v 
", v)
    default:
        fmt.Println("don't know")
    }
}

func main() {
    moo(21)
    moo("hello")
    moo(true)
}

However, this resulted in a syntax error related to the struct type (not seen if the case statement checking for the struct type is removed:

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

Is there a reason why the struct type cannot be checked for here? Note that the func moo() is checking for i of type interface{}, an empty interface which should supposedly be implemented by every type, including struct

Go Playground full code:

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

  • 写回答

1条回答 默认 最新

  • dqfwcj0030 2017-02-28 08:14
    关注

    struct is not a type, it's a keyword.

    This is a type for example (given using a type literal):

    struct { i int }
    

    Or Point:

    type Point struct { X, Y int }
    

    So the following code works:

    switch v := i.(type) {
    case struct{ i int }:
        fmt.Printf("Life is complicated with %v 
    ", v)
    case Point:
        fmt.Printf("Point, X = %d, Y = %d 
    ", v.X, v.Y)
    }
    

    You may look at struct as being a kind of type, which you can check using reflection, for example:

    var p Point
    if reflect.TypeOf(p).Kind() == reflect.Struct {
        fmt.Println("It's a struct")
    }
    

    Try it on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝