Skip to main content

Return Values

A function can send a value back to its caller. For that, declare the data type of the value being returned (int, string and so on) in the function signature, and use the return keyword in the function body.

Return Value Syntax

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

Function Return Example

This myFunction() takes two integers, x and y, adds them (x + y) and returns the sum as an int.

Example

Prompt
Create a function myFunction that takes two ints and returns their sum. Print the result of calling it with 1 and 2.
Output: Go program and captured output

Named Return Values

Go also lets you give a return value a name.

In this example, the return value is called result and has the type int. Because it already has a name, a plain return is enough. Using return without a variable name like this is known as a naked return.

Example

Prompt
Create a function with a named return value called result. Add two int parameters and use a naked return statement.
Output: Go program and captured output

Store the Return Value in a Variable

Rather than printing a function's result directly, you can keep it in a variable for later use.

Example

Prompt
Create a function with a named return value. Store the returned value in a variable called total and print it.
Output: Go program and captured output

Multiple Return Values

A Go function isn't limited to one return value; it can return several at once.

Example

This myFunction() gives back two values: an integer called result and a string called txt1.

Prompt
Create a function that returns both an int and a string. Pass 5 and "Hello", return x+x and y+" World!". Print both values.
Output: Go program and captured output

Example

The two returned values can be assigned to two variables at once, in this case a and b.

Prompt
Store multiple return values from a function in separate variables a and b, then print them.
Output: Go program and captured output

Example

Sometimes you only need part of what a function returns. Write an underscore (_) in place of a value you want to leave out. Here it drops the first value.

Prompt
Use the blank identifier _ to omit the first return value from a function that returns two values. Print only the string.
Output: Go program and captured output

Example

This time the underscore takes the second position, so the second returned value (txt1) is ignored.

Prompt
Use the blank identifier _ to omit the second return value. Print only the int result.
Output: Go program and captured output