英文:
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!")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论