Golang 返回多个值的函数

Golang 返回多个值的函数

在Go语言中,你可以使用返回语句从一个函数中返回多个值。或者换句话说,在函数中,一个返回语句可以返回多个值。返回值的类型与参数列表中定义的参数的类型相似。

语法

func function_name(parameter_list)(return_type_list){
     // code...
}

这里。

  • function_name: 它是函数的名称。
  • parameter-list: 它包含函数参数的名称和类型。
  • return_type_list: 它是可选的,它包含了函数返回值的类型。如果你在你的函数中使用return_type,那么有必要在你的函数中使用一个return语句。

例子

// Go program to illustrate how a
// function return multiple values
package main
  
import "fmt"
  
// myfunc return 3 values of int type
func myfunc(p, q int)(int, int, int ){
    return p - q, p * q, p + q 
}
  
// Main Method
func main() {
      
    // The return values are assigned into 
    // three different variables
   var myvar1, myvar2, myvar3 = myfunc(4, 2)
     
   // Display the values
   fmt.Printf("Result is: %d", myvar1 )
   fmt.Printf("\nResult is: %d", myvar2)
   fmt.Printf("\nResult is: %d", myvar3)
}

输出

Result is: 2
Result is: 8
Result is: 6

给返回值起名

在Go语言中,你可以为返回值提供名称。你也可以在你的代码中使用这些变量名。没有必要把这些名字写在返回语句中,因为Go编译器会自动理解这些变量必须被派送回来。而这种类型的返回被称为裸返回。裸返回可以减少你程序中的重复部分。

语法

func function_name(para1, para2 int)(name1 int, name2 int){
    // code...
}

**or**

func function_name(para1, para2 int)(name1, name2 int){
   // code...
}

这里,name1和name2是返回值的名称,para1和para2是该函数的参数。

例子

// Go program to illustrate how to
// give names to the return values
package main
  
import "fmt"
  
// myfunc return 2 values of int type
// here, the return value name 
// is rectangle and square
func myfunc(p, q int)( rectangle int, square int ){
    rectangle = p*q
    square = p*p
    return  
}
  
func main() {
      
    // The return values are assigned into 
    // two different variables
   var area1, area2 = myfunc(2, 4)
     
   // Display the values
   fmt.Printf("Area of the rectangle is: %d", area1 )
   fmt.Printf("\nArea of the square is: %d", area2)
     
}

输出

Area of the rectangle is: 8
Area of the square is: 4

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程