Go Function Returns

In the Go programming language, functions are capable of returning values, which allows us to capture and use those results elsewhere in our code. To enable this, we define the return type when declaring the function and use the return keyword inside the function to specify what will be sent back.

Tutorials dojo strip



Basic Function Return

When creating a function that returns a value, we specify the expected data type in the function definition.

Syntax:

Go




Example:

In this example, computeMileage() receives two integer values representing initial and additional mileage, then returns their sum.

Go

Output:

Go




Named Return Values

Go allows us to name return values directly in the function signature. This makes the code more readable.

Example:

Here, the function calculateTotalPrice() has a named return variable totalCost, which is assigned a value and returned without explicitly specifying it in the return statement.

Go

Output:

Go


We can also explicitly return the named variable:

Go

Output:

Go




Storing Returned Values in Variables

Instead of printing the return value directly, we can store it in a variable for further use.

Example:

Here, we store the total cost returned by calculateTotalPrice() in a variable called finalAmount.

Go

Output:

Go




Multiple Return Values

Functions in Go can return more than one value, which is useful when we need multiple outputs.

Example:

In this example, motorcycleDetails() returns both a price and a brand name.

Go

Output:

Go


We can also store the returned values into separate variables:

Go

Output:

Go




Omitting Unused Returned Values

If we only need one of the returned values, we can use an underscore (_) to discard the unused one.

Example:

Omitting the price and keeping the brand name:

Go

Output:

Go


Omitting the brand name and keeping the price:

Go

Output:

Go

Tutorials dojo strip