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 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?