To return multiple values from a function in Go, simply specify the data types of the return values separated by commas in the function signature. Then in the function body, use the return
statement followed by a comma-separated list of the corresponding values.
Here's an example of a function that accepts two integers and returns their sum and difference:
main.go69 chars4 lines
To call this function, you can do the following:
main.go138 chars4 lines
In the above example, the function signature (int, int)
specifies that two integers will be returned. Then, in the return
statement, we provide a comma-separated list of the values to be returned a+b, a-b
. Finally, we capture the returned values by assigning them to sum
and diff
variables respectively using Go's multiple assignment feature.
gistlibby LogSnag