Golang中的switch语句出现了”used as value”错误?

huangapple go评论90阅读模式
英文:

golang switch got an ` used as value` error?

问题

我不太清楚为什么 switch t := some.(type){} 能正常工作,但如果我尝试 switch k := f.Kind(){} 或类似的代码,会出现以下错误:

.\mym.go:58: k := f.Kind() 作为值使用

退出状态 2

英文:

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

得分: 4

是的,你是对的,这是语法错误;应该是SimpleStmt或ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}"。
参考:
https://golang.org/ref/spec#Switch_statements
在表达式switch中,case包含与switch表达式的值进行比较的表达式。
以下代码将正常工作:

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()) //语法错误:意外的:=,期望逗号或)
	switch k := f.Kind(); k {
	case 12:
		fmt.Println(k) //12
	case 0:
		fmt.Println("Bye!")
	}
}
英文:

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!")
	}
}

huangapple
  • 本文由 发表于 2016年4月23日 15:24:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/36807948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定