Go language functions support returning multiple values, separated by commas in type declarations. Use x, y := myFunction() to get the return value. For example, the calculateRectangle function returns area and perimeter, which can be obtained respectively through area, perimeter := calculateRectangle(length, width). Return values can be named to improve readability. If you are not interested in part of the return value, you can use underscores to ignore it.
In Go language, functions can return multiple values. This is useful for situations where multiple related pieces of information need to be returned simultaneously.
To return multiple values, just use commas to separate the types in the function signature, like this:
func myFunction() (int, string) { return 1, "hello" }
To get multiple return values from a function, use the following syntax:
x, y := myFunction()
x
andy
will respectively receive the first one returned by the function and the second value.
Consider a function that calculates the area and perimeter of a rectangle:
func calculateRectangle(length, width int) (int, int) { area := length * width perimeter := 2 * (length + width) return area, perimeter }
In the main function, we can use this function as follows:
func main() { length := 5 width := 10 area, perimeter := calculateRectangle(length, width) fmt.Printf("Area: %d, Perimeter: %d\n", area, perimeter) }
In some cases, named return values may be useful. This can make the code more readable and maintainable.
func calculateRectangle(length, width int) (area, perimeter int) { area = length * width perimeter = 2 * (length + width) return }
If you are not interested in some return values of a function, you can use the underscore (_) to ignore them.
_, perimeter := calculateRectangle(length, width)
The above is the detailed content of Handling of multiple return values from golang functions. For more information, please follow other related articles on the PHP Chinese website!