提供 if 语句返回的函数结果问题解决方案。

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

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:

huangapple
  • 本文由 发表于 2013年11月20日 22:52:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/20099144.html
匿名

发表评论

匿名网友

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

确定