英文:
Provide function return from an if statement issues
问题
我在golang中遇到了一个问题,无法从if语句中返回函数的预期返回语句。
我提供了下面的代码:
package main
import (
"fmt"
)
func random() string {
var x = "return"
if x == "return" {
return x
}
}
func main() {
fmt.Println(random())
}
难道主函数不应该打印出random函数返回的字符串值吗?我得到的只是:
go.go:13: missing return at end of function
有人知道如何解决这个问题吗?
英文:
I'm having trouble returning a function's expected return statement from within an if statement in golang.
I have provided the code below:
package main
import (
"fmt"
)
func random() string {
var x = "return"
if x == "return" {
return x
}
}
func main() {
fmt.Println(random())
}
Shouldn't the main function print out the string value returned by the random function?All i get is
go.go:13: missing return at end of function
Does anybody have a clue how to make this happen?
答案1
得分: 10
你必须在最后加上一个return
语句,即使它从未被使用,如果函数返回一个值:
func random() string {
var x = "return"
if x == "return" {
return x
}
return ""
}
func main() {
fmt.Println(random())
}
你可以在这里查看代码:http://play.golang.org/p/XFsPL2G15R
英文:
You have to include a return
at the end, even if it is never used, if the function returns a value:
http://play.golang.org/p/XFsPL2G15R
func random() string {
var x = "return"
if x == "return" {
return x
}
return ""
}
func main() {
fmt.Println(random())
}
答案2
得分: 8
在Go 1.1中,你不需要在函数末尾添加return,但你需要一个"终止语句",这段代码应该可以工作:
func random() string {
var x = "return"
if x == "return" {
return x
} else {
return "else"
}
}
func main() {
fmt.Println(random())
}
更多信息,请参考:
英文:
In Go 1.1, you don't need to add return at the end of function all the time, but you need a Terminating statement, this code should work:
http://play.golang.org/p/fNiijqNHbt
func random() string {
var x = "return"
if x == "return" {
return x
} else {
return "else"
}
}
func main() {
fmt.Println(random())
}
For more infomation, see:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论