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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题