Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go函数多个返回值实例
Go函数多个返回值实例
作者:--    发布时间:2019-11-20

go内置支持多个返回值。此功能经常用于通用的go中,例如从函数返回结果和错误值。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

此函数签名中的(int,int)表示函数返回2int类型值。
这里使用从多个赋值的调用返回2个不同的值。如果只想要返回值的一个子集,请使用空白标识符_
接受可变数量的参数是go函数的另一个不错的功能; 在接下来实例中可以来了解和学习。

multiple-return-values.go的完整代码如下所示 -

package main

import "fmt"

// the `(int, int)` in this function signature shows that
// the function returns 2 `int`s.
func vals() (int, int) {
    return 3, 7
}

func main() {

    // here we use the 2 different return values from the
    // call with _multiple assignment_.
    a, b := vals()
    fmt.println(a)
    fmt.println(b)

    // if you only want a subset of the returned values,
    // use the blank identifier `_`.
    _, c := vals()
    fmt.println(c)
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run multiple-return-values.go
3
7
7

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册