dongzhaobai5982 2016-04-23 07:24
浏览 43
已采纳

Golang开关有一个`用作值`错误?

I don't know really why switch t := some.(type){} works well, but if I tried switch k := f.Kind(){} or so on.

.\mym.go:58: k := f.Kind() used as value

exit status 2
  • 写回答

1条回答 默认 最新

  • dsgfdgh14569 2016-04-23 08:00
    关注

    Yes you are right, it is syntax error; it should be SimpleStmt or ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
    see: https://golang.org/ref/spec#Switch_statements
    In an expression switch, the cases contain expressions that are compared against the value of the switch expression. And this will work:

    package main
    
    import (
        "fmt"
    )
    
    type Test struct {
        kind int
    }
    
    func (s *Test) Kind() int {
        return s.kind
    }
    func main() {
        f := &Test{12}
        //fmt.Println(k := f.Kind()) //syntax error: unexpected :=, expecting comma or )
        switch k := f.Kind(); k {
        case 12:
            fmt.Println(k) //12
        case 0:
            fmt.Println("Bye!")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态