Home >Backend Development >Golang >Return value of golang function

Return value of golang function

WBOY
WBOYOriginal
2024-04-19 17:21:02571browse

Go language functions can use the return statement to return multiple values, which are received by specifying variables after calling the function. The number and type of return values ​​must be explicitly specified in the function declaration, and the function can return any number of values ​​(but cannot return null).

Return value of golang function

The return value of Go language function

Go language function can use the return statement to return multiple value. The return value is received through the variable specified in parentheses after calling the function.

Syntax:

func functionName(parameterList) (returnType1, returnType2, ...) {
    // 函数体
    return value1, value2, ...
}

Example:

The following function calculates the sum and difference of two numbers:

func calc(a, b int) (sum, diff int) {
    sum = a + b
    diff = a - b
    return
}

Practical case:

The following code uses the calc function to calculate the sum and difference of two numbers entered by the user:

package main

import (
    "fmt"
)

func main() {
    var a, b int
    fmt.Print("输入第一个数字: ")
    fmt.Scanln(&a)
    fmt.Print("输入第二个数字: ")
    fmt.Scanln(&b)

    sum, diff := calc(a, b)
    fmt.Printf("和:%d\n", sum)
    fmt.Printf("差:%d\n", diff)
}

Description:

  • Multiple return values ​​must specify the type.
  • return Each value following the statement corresponds to a return value of the type specified in the function declaration.
  • The function can return any number of values, but it cannot return a null value.

The above is the detailed content of Return value of golang function. 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