Function Returns

Go Functions: Function Returns #

Functions in Go can return values. To do this, you need to define the return type and use the return keyword inside the function.


Function Return Syntax #

Syntax:

func FunctionName(param1 type, param2 type) type {
    // code to be executed
    return output
}

Example: Single Return Value #

package main
import "fmt"

func myFunction(x int, y int) int {
    return x + y
}

func main() {
    fmt.Println(myFunction(1, 2))
}

Result:

3

Named Return Values #

You can name the return value in Go. This allows the use of a naked return, which returns the named variable automatically.

Example:

package main
import "fmt"

func myFunction(x int, y int) (result int) {
    result = x + y
    return
}

func main() {
    fmt.Println(myFunction(1, 2))
}

Result:

3

You can also explicitly return the named variable:

return result

Storing Return Value in a Variable #

package main
import "fmt"

func myFunction(x int, y int) (result int) {
    result = x + y
    return
}

func main() {
    total := myFunction(1, 2)
    fmt.Println(total)
}

Result:

3

Multiple Return Values #

Go allows functions to return multiple values.

Example:

package main
import "fmt"

func myFunction(x int, y string) (result int, txt1 string) {
    result = x + x
    txt1 = y + " World!"
    return
}

func main() {
    fmt.Println(myFunction(5, "Hello"))
}

Result:

10 Hello World!

Storing Multiple Return Values #

package main
import "fmt"

func myFunction(x int, y string) (result int, txt1 string) {
    result = x + x
    txt1 = y + " World!"
    return
}

func main() {
    a, b := myFunction(5, "Hello")
    fmt.Println(a, b)
}

Result:

10 Hello World!

Omitting Return Values #

If you want to ignore a returned value, use the underscore _.

Omit first value:

_, b := myFunction(5, "Hello")
fmt.Println(b)

Result:

Hello World!

Omit second value:

a, _ := myFunction(5, "Hello")
fmt.Println(a)

Result:

10

Functions with return values make Go programs flexible, allowing results to be reused, stored, or passed to other functions.