English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Golang basic tutorial

Golang control statement

Golang function & method

Golang struct

Golang slice & array

Golang string(String)

Golang pointer

Golang interface

Golang concurrency

Golang exception(Error)

Golang other items

Multiple return values in Go language function

In Go language, you are allowed to use the return statement to return from a functionfunctionreturn multiple values. In other words, in a function, a single return statement can return multiple values. The type of the return values is similar to the type of the parameters defined in the parameter list.

Syntax:

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

here,

  • function_name:isfunctionname.

  • parameter-list:It contains the names and types of the function parameters.

  • return_type_list:This is optional, it contains the type of the values returned by the function. If you use return_type in the function, you must use a return statement in the function.

package main
import "fmt"
// myfunc returns3values of type int
func myfunc(p, q int) (int, int, int) {
    return p - q, p * q, p + q
}
func main() {
    //assign the return value to, three different variables
    var myvar1, myvar2, myvar3 = myfunc(4, 2)
    // display the value
    fmt.Printf("Result is: %d", myvar)1)
    fmt.Printf("\nResult is: %d", myvar)2)
    fmt.Printf("\nResult is: %d", myvar)3)
}

Output:

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

Naming return values

In Go language, it is allowed to provide names for return values. You can also use these variable names in the code. There is no need to write these names with a return statement, because the Go compiler will automatically understand that these variables must be assigned back. This type of return is called a naked return. Simple returns reduce repetition in the program.

Syntax:

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

here,name1andname2are the names of the return values, while para1and para2are the function parameters.

package main
import "fmt"
// myfunc returns2values of type int
//Here is the name of the return value
//are rectangle and square
func myfunc(p, q int) (rectangle int, square int) {
    rectangle = p * q
    square = p * p
    return
}
func main() {
    //assign the return value to
    //two different variables
    var area1, area2 = myfunc(2, 4)
    fmt.Printf("Area of rectangle: %d", area)1)
    fmt.Printf("\nArea of square: %d", area)2)
}

Output:

Rectangle Area: 8
Square Area: 4