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
}
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.
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
clausearr := []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 {
...
}
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)
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