Google News
logo
Golang - Interview Questions
Is it possible to return multiple values from a function in Go?
Yes. Multiple values can be returned in Golang by sending comma-separated values with the return statement and by assigning it to multiple variables in a single statement as shown in the example below:
package main
import (
	"fmt"
)

func reverseValues(a,b string)(string, string){
    return b,a    //notice how multiple values are returned
}

func main(){
    val1,val2:= reverseValues("freetime","learning")    // notice how multiple values are assigned
    fmt.Println(val1, val2)
}
In the above example, we have a function reverseValues which simply returns the inputs in reverse order. In the main goroutine, we call the reverseValues function and the values are assigned to values val1 and val2 in one statement. The output of the code would be
learning freetime
Advertisement