Home > Article > Backend Development > How does a Golang function return multiple values?
Functions in Go can return multiple values through multiple variables separated by commas. The syntax is: func functionName(parameters) (returnValue1, returnValue2, ..., returnValueN type) {}. Example: func squareAndCube(num int) (int, int) { return num * num, num * num * num } Returns the square and cube.
In Go, a function can return multiple values by passing multiple variables separated by a comma delimiter. . This is different from returning a single value, which uses a separate variable.
The syntax of a function that returns multiple values is as follows:
func functionName(parameters) (returnValue1, returnValue2, ..., returnValueN type) { // 函数体 }
Among them, returnValue1
, returnValue2
, etc. are return variables name and type.
Consider a function that calculates the square and cube of a number:
import "fmt" // 计算数的平方和立方 func squareAndCube(num int) (int, int) { square := num * num cube := num * num * num return square, cube } func main() { number := 5 square, cube := squareAndCube(number) fmt.Printf("平方: %d, 立方: %d", square, cube) }
In the main function, the squareAndCube
function is called, It returns two values square
and cube
. These values are then assigned to the square
and cube
variables. Finally, use the fmt.Printf
function to print out the square and cube.
Output:
平方: 25, 立方: 125
The above is the detailed content of How does a Golang function return multiple values?. For more information, please follow other related articles on the PHP Chinese website!