Home  >  Article  >  Backend Development  >  How does a Golang function return multiple values?

How does a Golang function return multiple values?

WBOY
WBOYOriginal
2024-04-11 21:33:011188browse

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.

How does a Golang function return multiple values?

How a function returns multiple values ​​in Go

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.

Syntax

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.

Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn