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 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题