📜  使用多个返回值的 Golang 程序

📅  最后修改于: 2021-10-25 02:39:29             🧑  作者: Mango

在 Golang 中,我们可以从单个函数一次返回多个值。通过在函数签名中改变函数的返回类型,可以实现多个返回值。

句法 :

func value( ) ( int , int ) { 
return 1 , 0 ; 
} 

此函数签名中的 (int, int) 说明返回类型是两个整数。因此我们在调用这个函数时必须使用多个赋值。此功能还用于从函数返回结果和错误。如果您需要返回值子集,请使用空白标识符_

示例 1:使用此功能查找两个元素的最大值和最小值:

GO
package main
  
import "fmt"
  
// declaring a function
// having return type 
// of int, int
func maxmin(a int, b int) (int, int) {
  
    if a > b {
      
        // separate multiple return
        // values using comma
        return a, b
    } else {
  
        return b, a
    }
    // this function returns 
    // maximum , minimum values
}
  
func main() {
  
    // declaring two values a and b
    var a = 50
    var b = 70
  
    // calling the function
    // with multiple assignments
    var max, min = maxmin(a, b)
  
    // Printing the values
    fmt.Println("Max = ", max, "\nMin = ", min)
}


GO
package main
  
import "fmt"
  
// declaring a function having
// return type of int, int
func sumDiff(a int, b int) (int, int) {
  
    return (a + b), (a - b)
  
    // this function returns sum ,
    // difference of the two numebrs
}
  
func main() {
  
    // declaring two values a and b
    var a = 68
    var b = 100
  
    // calling the function
    // with multiple assignments
    var sum, diff = sumDiff(a, b)
  
    // Printing the values
    fmt.Println("Sum = ", sum, "\nDifference = ", diff)
}


输出 :

Max =  70 
Min =  50

例2:求两个数的和和差,利用这个多返回值的特性。

package main
  
import "fmt"
  
// declaring a function having
// return type of int, int
func sumDiff(a int, b int) (int, int) {
  
    return (a + b), (a - b)
  
    // this function returns sum ,
    // difference of the two numebrs
}
  
func main() {
  
    // declaring two values a and b
    var a = 68
    var b = 100
  
    // calling the function
    // with multiple assignments
    var sum, diff = sumDiff(a, b)
  
    // Printing the values
    fmt.Println("Sum = ", sum, "\nDifference = ", diff)
}

输出 :

Sum =  168 
Difference =  -32