翻译进度
4
分块数量
1
参与人数

Return statements

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


函数 F 中的 return 语句终止F 函数的执行,并可以选择提供一个或多个结果值。在F中执行的所有延迟调用均在F返回其调用方之前执行。

ReturnStmt = "return" [ ExpressionList ] .

在没有返回值类型的函数中,return 语句不能指定任何返回值。

func noResult() {
    return
}
singee 翻译于 4年前

There are three ways to return values from a function with a result type:

  1. The return value or values may be explicitly listed in the "return" statement. Each expression must be single-valued and assignable to the corresponding element of the function's result type.

    func simpleF() int {
        return 2
    }
    
    func complexF1() (re float64, im float64) {
        return -7.0, -4.0
    }
  2. The expression list in the "return" statement may be a single call to a multi-valued function. The effect is as if each value returned from that function were assigned to a temporary variable with the type of the respective value, followed by a "return" statement listing these variables, at which point the rules of the previous case apply.

    func complexF2() (re float64, im float64) {
        return complexF1()
    }
  1. The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.
func complexF3() (re float64, im float64) {
    re = 7.0
    im = 4.0
    return
}

func (devnull) Write(p []byte) (n int, _ error) {
    n = len(p)
    return
}

无论如何声明函数,所有结果值在传入函数时都会被初始化为其类型的零值。return 语句指定的返回值将在执行任何延迟函数执行之前为结果变量赋值。

实现限制:如果作用域中具有与结果参数同名的另一个标识符(常量,类型或变量),则编译器可能不允许在返回语句中使用空表达式列表。

func f(n int) (res int, err error) {
    if _, err := f(n-1); err != nil {
        return  // 不合法的 return 表达式: err 被屏蔽
    }
    return
}
singee 翻译于 4年前

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~