How to get the return value of golang function?

WBOY
Release: 2024-04-22 16:06:02
Original
438 people have browsed it

Go language functions pass data through return values. To return a single value, simply specify the return value type in the function signature and use a variable to receive the return value when the function is called. To return multiple values, you need to use a tuple type in the function signature and use multiple variables to receive the return values ​​when calling the function.

How to get the return value of golang function?

#How do Go language functions get return values?

In the Go language, functions can pass data through return values. A function can return a single value, or multiple values, and the type of the return value must be specified in the function signature.

Return a single value

To return a single value, simply specify the return value type in the function signature as follows:

func myFunction() int {
    return 10
}
Copy after login

When calling the function, you can use variables Receive return value:

num := myFunction()
fmt.Println(num) // 输出:10
Copy after login

Return multiple values

To return multiple values, you need to use a tuple type in the function signature, as shown below:

func myFunction() (int, string) {
    return 10, "Hello"
}
Copy after login

In calling function, you can use multiple variables to receive return values:

num, str := myFunction()
fmt.Println(num, str) // 输出:10 Hello
Copy after login

Practical case: Calculate area

The following is an example of a function that calculates the area of ​​a rectangle:

func calculateArea(length, width float64) float64 {
    return length * width
}
Copy after login

In the main function , we can use this function and print the return value:

func main() {
    length := 5.0
    width := 2.5
    area := calculateArea(length, width)
    fmt.Println("矩形的面积为:", area) // 输出:矩形的面积为: 12.5
}
Copy after login

The above is the detailed content of How to get the return value of golang function?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template