create a function that returns multiple values in go

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.go
func sumAndDiff(a int, b int) (int, int) {
    return a + b, a - b
}
69 chars
4 lines

To call this function, you can do the following:

main.go
sum, diff := sumAndDiff(10, 5)
fmt.Println("Sum:", sum)      // Output: Sum: 15
fmt.Println("Difference:", diff) // Output: Difference: 5
138 chars
4 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