Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查go中是否存在else条件时未定义变量名_Go - Fatal编程技术网

检查go中是否存在else条件时未定义变量名

检查go中是否存在else条件时未定义变量名,go,Go,我在学习教程时编写了以下程序。这是关于检查go中的条件的 但是,它会抛出错误作为未定义消息。请帮忙 //查看各种条件运算符 包干管 输入“fmt” func条件(x int)字符串{ 如果x>5{ 消息:=“x大于5” }如果x==5,则为else{ 消息:=“x等于5” }否则{ 消息:=“x小于5” } 返回消息//此行出错 } func main(){ x:=10-5 msg:=条件(x) 格式打印项次(“%s”,msg) } 输出接收为: user$ go run condition

我在学习教程时编写了以下程序。这是关于检查
go
中的条件的
但是,它会抛出错误作为
未定义消息
。请帮忙


//查看各种条件运算符
包干管
输入“fmt”
func条件(x int)字符串{
如果x>5{
消息:=“x大于5”
}如果x==5,则为else{
消息:=“x等于5”
}否则{
消息:=“x小于5”
}
返回消息//此行出错
}
func main(){
x:=10-5
msg:=条件(x)
格式打印项次(“%s”,msg)
}
输出接收为:

user$ go run conditionals.go 
# command-line-arguments
./conditionals.go:15:9: undefined: message

问题是您在一个范围内定义了
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)
}

消息的范围在每个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
}

在第二个代码块中,赋值必须是:
m=“x大于5”
而不是
message=“x大于5”