I have the following code.
package main
import "fmt"
func main() {
a := 0
b := 0
a, b += getValues()
fmt.Println(a, b)
}
func getValues() (a int, b int) {
a = 0
b = 5
return
}
I want to directly add the multiple values returned by a function. I just want to if there is a provision like this in Go.
When I run the above code, I get the following error.
syntax error: unexpected +=, expecting := or = or comma
You can use a helper method which takes a variadic number of parameters and just returns the slice created from the params
func aggregator(res ...interface{}) []interface{}{
return res
}
If you want to escape the extra type assertion you can set the type you want to work with, in your case int
, for the input and output parameters of the helper function. But here is an example using interface{}
:
func main() {
fmt.Printf("%d, %d", aggregator(f())[0].(int), aggregator(f())[1].(int))
}
func aggregator(res ...interface{}) []interface{}{
return res
}
func f () (int, int) {
return 1,2
}