检查 go 中的 if-else 条件时未定义的变量名称
时间:2024-04-14
浏览:322
作者:佚名
一分耕耘,一分收获!既然打开了这篇文章《检查 go 中的 if-else 条件时未定义的变量名称》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!
问题内容
我在学习教程时编写了以下程序。这是关于检查 go 中的条件。
但是,它会抛出错误,如 undefined message。请帮忙。
// check out various conditional operators
package main
import "fmt"
func condition(x int) string {
if x > 5 {
message := "x is greater than 5"
} else if x == 5 {
message := "x is equal to 5"
} else {
message := "x is less than 5"
}
return message // error on this line
}
func main() {
x := 10 - 5
msg := condition(x)
fmt.println("%s", msg)
}
输出接收为:
user$ go run conditionals.go # command-line-arguments ./conditionals.go:15:9: undefined: message
解决方案
message 的作用域为每个 if/else 分支。您希望它的范围在函数级别:
func condition(x int) string {
var message string
if x > 5 {
message = "x is greater than 5"
} else if x == 5 {
message = "x is equal to 5"
} else {
message = "x is less than 5"
}
return message
}
由于您要返回此值,因此您可以更新函数签名以包含返回的变量,例如
func condition(x int) (m string) {
if x > 5 {
m = "x is greater than 5"
}
// ...
return // implicitly returns m value
}问题是您在范围内(即大括号内)定义了 message,而您的 return 语句位于这些括号之外。解决方案是在与 return 语句相同的范围内定义 message,然后在每个条件子句中重新定义 message。
package main
import "fmt"
func condition(x int) string {
message := ""
if x > 5 {
message = "x is greater than 5"
} else if x == 5 {
message = "x is equal to 5"
} else {
message = "x is less than 5"
}
return message
}
func main() {
x := 10 - 5
msg := condition(x)
fmt.Println(msg)
}
https://play.golang.org/p/z_8h0ISNKYO
今天关于《检查 go 中的 if-else 条件时未定义的变量名称》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
