Go函数多个返回值实例

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

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.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



上一篇:Go函数实例

下一篇:Go可变参数的函数实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程