bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Go/Go Tutorial
Go•Go Tutorial

Go Function Returns

Return Values

If you want the function to return a value, you need to define the data type of the return value (such as int , string , etc), and also use the return keyword inside the function:

Syntax

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

Function Return Example

myFunction()

Named Return Values

In Go, you can name the return values of a function.

result

The example above can also be written like this. Here, the return statement specifies the variable name:

Example

package main
import ("fmt")
func myFunction(x int, y int) (result int) {
 result = x + y
 return result
}
func main() {
 fmt.Println(myFunction(1, 2))
}

Store the Return Value in a Variable

You can also store the return value in a variable, like this:

total

Multiple Return Values

Go functions can also return multiple values.

myFunction()
a

If we (for some reason) do not want to use some of the returned values, we can add an underscore ( _ ), to omit this value.

result
txt1

Previous

Go Function Parameters and Arguments

Next

Go Recursion Functions