函数末尾缺少返回语句,即使条件是穷尽的。

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

Missing return at end of function even if conditions are exhaustive

问题

以下是您提供的代码的翻译:

package main

import (
	"fmt"
)

func main() {
	fmt.Println(test(1, 2))
}

func test(a, b int) bool {
	if a == b {
		return true
	}
	if a > b {
		return true
	}
	if a < b {
		return false
	}
}

运行上述代码后,我得到了以下错误信息:

./main.go:21:1: 函数末尾缺少返回语句

我的问题是,在函数test中,所有的情况都有返回语句,为什么还需要在函数末尾添加返回语句?

英文:
package main

import (
	&quot;fmt&quot;
)

func main() {
	fmt.Println(test(1, 2))
}

func test(a, b int) bool {
	if a == b {
		return true
	}
	if a &gt; b {
		return true
	}
	if a &lt; b {
		return false
	}
}

run above code i get the follow wrong message:

./main.go:21:1: missing return at end of function

my question is in function test, all the situation is return. why also need return at end of function.

答案1

得分: 8

这是由语言规范所规定的(来源):

如果函数的签名声明了结果参数,函数体的语句列表必须以终止语句结束。

终止语句的定义如下:

一个包含以下条件的“if”语句:

  • 存在“else”分支,并且
  • 两个分支都是终止语句。

你的if语句没有else分支,所以你的函数体缺少终止语句,即使被测试的条件可能是穷尽的。

你必须在函数体末尾添加一个显式的return语句,或者重写为if-else语句(仅使用else if是不够的):

func test(a, b int) bool {
    // 这是一个终止语句
    if a == b {
        return true
    } else if a > b {
        return true
    } else /* a < b */ {
        return false
    }
}

然而,这种if-大于或等于的情况可以简化为:

return a >= b
英文:

This is regulated by the language specifications (source):

> If the function's signature declares result parameters, the function body's statement list must end in a terminating statement.

And a terminating statement is defined as:

> An "if" statement in which:
> - the "else" branch is present, and
> - both branches are terminating statements.

Your if statements do not have an else branch, so your function body is missing the terminating statement, even if the conditions being tested may be exhaustive.

You must either add an explicit return at the end of the function body, or rewrite as an if-else (only else if is not enough):

func test(a, b int) bool {
    // this is a terminating statement
    if a == b {
        return true
    } else if a &gt; b {
        return true
    } else /* a &lt; b */ {
        return false
    }
}

However this kind of if-greater-or can be just written as:

return a &gt;= b

huangapple
  • 本文由 发表于 2022年7月1日 15:27:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/72825747.html
匿名

发表评论

匿名网友

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

确定