# Golang初级系列教程-函数多个返回值

19 篇文章 1 订阅
18 篇文章 0 订阅

## Golang函数多个返回值

Go 允许函数有多个返回值，其定义结构如下：

func SumProdDiff(i, j int) (int, int, int)

return sum, prod, diff

s, p, d := SumProdDiff(value1, value2)

func SumProdDiff(i, j int) (s int, p int, d int)

### 多个返回值

package main

import (
"fmt"
)

func SumProductDiff(i, j int) (int, int, int) {
return i+j, i*j, i-j
}

func main() {
sum, prod, diff := SumProductDiff(3,4)
fmt.Println("Sum:", sum, "| Product:",prod, "| Diff:", diff)
}
Sum: 7 | Product: 12 | Diff: -1

### 通过多个返回值处理错误

retValue, err := my_function()
if err == nil { //go ahead with normal code
} else { //error handling code
}

package main

import (
"fmt"
"errors"
"math"
)

func MySqrt(f float64) (float64, error) {
//return an error as second parameter if invalid input
if (f < 0) {
return float64(math.NaN()), errors.New("I won't be able to do a sqrt of negative number!")
}

//otherwise use default square root function
return math.Sqrt(f), nil
}

func main() {
fmt.Print("First example with -1: ")
ret1, err1 := MySqrt(-1)
if err1 != nil {
fmt.Println("Error! Return values are", ret1, err1)
} else {
fmt.Println("It's ok! Return values are", ret1, err1)
}

fmt.Print("Second example with 5: ")
//you could also write it like this
if ret2, err2 := MySqrt(5); err2 != nil {
fmt.Println("Error! Return values are", ret2, err2)
} else {
fmt.Println("It's ok! Return values are", ret2, err2)    }
}
First example with -1: Error! Return values are NaN I won't be able to do a sqrt of negative number!
Second example with 5: It's ok! Return values are 2.23606797749979

### 返回值命名

Go 允许在定义函数时，命名返回值，当然这些变量可以在函数中使用。在 return 语句中，无需显示的返回这些值，Go 会自动将其返回。当然 return 语句还是必须要写的，否则编译器会报错。

package main

import (
"fmt"
"errors"
"math"
)

//name the return variables - by default it will have 'zero-ed' values i.e. numbers are 0, string is empty, etc.
func MySqrt2(f float64) (ret float64, err error) {
if (f < 0) {
//then you can use those variables in code
ret = float64(math.NaN())
err = errors.New("I won't be able to do a sqrt of negative number!")
} else {
ret = math.Sqrt(f)
//err is not assigned, so it gets default value nil
}
//automatically return the named return variables ret and err
return
}

func main() {
fmt.Println(MySqrt2(5))
}
2.23606797749979 <nil>

Golang一种神奇的语言，让我们一起进步

• 4
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
08-13
09-16
07-31 3774
10-22 454
03-05 403
07-17 309
03-12 1805
04-13 891
03-17 191
01-17 3023

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。