Search code examples
functiongoreturnvariable-assignment

Is it possible to return a different number of values based on how many variables are assigned to the function?


I have a function, foo(), that returns an int and a bool, the bool being whether or not the function executed properly. If the caller only wants the int, he can type value, _ := foo(). Is there a way to set it so that the caller can just type value := foo() and it automatically only returns the int, like how range can return either the index and value, or just the index?

Example code:

func foo(num int) (int, bool) {
    if num % 2 == 1 {
        //function fails
        return 0, false
    }

    //function succeeds
    return num + 5, true
}

func main() {
    value1, _ := foo(6) //works

    value2 := foo(6) //assignment mismatch
}

Solution

  • Special features of the Go programming language include maps, type assertions, for statement with a range clause and channel receives have variable number of return values. But the number of return values cannot be variable for a regular function type.

    • Maps
    m := make(map[string]int)
    
    m["one"] = 1
    
    // Return value is the value in the map for the given key.
    val := m["one"] 
    
    // First return value is the value in the map for the given
    // key and second return value indicates if the key was
    // present in the map.
    val,ok := m["one"]
    
    • for statement with a range clause
    arr := []int{1, 2, 3, 4}
    
    // Return value is the index.
    for idx := range arr {
     ...
    }
    
    // First return value is the index and second return 
    // value is a copy of the element at that index.
    for idx, val := range arr {
     ...
    }
    
    • Type assertions
    
    var i interface{}
    i = 1
    
    // First return value is the underlying value and second
    // return value is a boolean value that reports whether the
    // assertion succeeded or not.
    num, ok := i.(int)
    
    // Return value is the underlying value.
    num := i.(int)
    
    
    • Channels receives
    c := make(chan int, 2)
    
    c <- 12
    c <- 21
    
    // Return value indicates the received value from the channel.
    val := <-c
    
    // First return value is the received value from the
    // channel. Second return value is a boolean which indicates
    // if there are no more values to receive and the channel is
    // closed or not.
    val, ok := <-c