gpt4 book ai didi

如果没有无法访问的 return 语句,Go 代码将无法编译

转载 作者:IT老高 更新时间:2023-10-28 13:04:17 26 4
gpt4 key购买 nike

这是在 Go 中求一个数的阶乘的程序:

func factorial(x uint) uint {
if x == 0 {
return 1
}

return x * (factorial(x - 1))
}

在输入 5 上调用此函数时的输出为 120。但是,如果我添加 else 语句,则会出现错误。

func factorial(x uint) uint {
if x == 0 {
return 1
} else {
return x * (factorial(x - 1))
}
}

错误:函数结束时没有返回语句

我在最后加了一个return:

func factorial(x uint) uint {
if x == 0 {
return 1
} else {
return x * (factorial(x - 1))
}
fmt.Println("this never executes")
return 1
}

我得到了 120 的预期输出。

为什么第二种情况会导致错误?为什么在第三种情况下,即使函数从未到达最后一个 return 1,它也会计算正确的输出?

最佳答案

这是一个众所周知的编译器问题。

甚至记录了一个问题:http://code.google.com/p/go/issues/detail?id=65

用 Go 语言的一位作者的话来说:

The compilers require either a return or a panic to be lexically last in a function with a result. This rule is easier than requiring full flow control analysis to determine whether a function reaches the end without returning (which is very hard in general), and simpler than rules to enumerate easy cases such as this one. Also, being purely lexical, the error cannot arise spontaneously due to changes in values such as constants used in control structures inside the function.

-rob

来自另一条评论 in golang-nuts ,我们可以推断它不会很快被“修复”:

It's not a bug, it's a deliberate design decision.

-rob

请注意,Java 等其他语言的规则允许此else


2013 年 3 月编辑 - 只是 got changed in Go1.1 :

Before Go 1.1, a function that returned a value needed an explicit "return" or call to panic at the end of the function; this was a simple way to make the programmer be explicit about the meaning of the function. But there are many cases where a final "return" is clearly unnecessary, such as a function with only an infinite "for" loop.

In Go 1.1, the rule about final "return" statements is more permissive. It introduces the concept of a terminating statement, a statement that is guaranteed to be the last one a function executes. Examples include "for" loops with no condition and "if-else" statements in which each half ends in a "return". If the final statement of a function can be shown syntactically to be a terminating statement, no final "return" statement is needed.

Note that the rule is purely syntactic: it pays no attention to the values in the code and therefore requires no complex analysis.

Updating: The change is backward-compatible, but existing code with superfluous "return" statements and calls to panic may be simplified manually. Such code can be identified by go vet.

我提到的问题现在以状态“已修复”关闭。

关于如果没有无法访问的 return 语句,Go 代码将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13516118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com