Can a function return multiple values?

0157

Yes, a function can return multiple values. In many programming languages, including Go, Python, and others, you can return multiple values by separating them with commas in the return statement. The caller can then capture these values using multiple assignment.

Here’s an example in Go:

package main

import "fmt"

// Function that returns two integers
func swap(a int, b int) (int, int) {
    return b, a
}

func main() {
    x, y := swap(1, 2) // x will be 2, y will be 1
    fmt.Println(x, y)  // Output: 2 1
}

In this example, the swap function returns two integers in reverse order, and the caller captures both values using multiple assignment.

0 Comments

no data
Be the first to share your comment!