Go Function Returns

Go Tutorial

 Go Function Returns – Complete Guide with Examples

In Go (Golang), functions can return values back to the caller. Returning values allows functions to produce results, share data, and build reusable logic.

Go has a powerful and flexible return system:

  • Single return value

  • Multiple return values

  • Named return values

  • Returning errors

  • Returning structs and slices

Let’s break it down step by step.


 What Is a Return Value in Go?

A return value is the output produced by a function using the return keyword.

Basic Syntax


 Returning a Single Value

Example

Usage

Output

30
  •  Simple and clear
  •  Most common use case

 Returning Multiple Values (Very Important)

Go allows functions to return multiple values, which is widely used.

Example

Usage

Output

9 20
  •  No need for objects or tuples
  •  Cleaner error handling

 Ignoring Return Values

Use _ to ignore unwanted return values.

  •  Avoids unused variable errors

 Returning Named Values

Go supports named return values.

Example

  • return without values
  •  Readable but should be used carefully

 Returning an Error (Very Common)

Error handling is a core Go feature.

Example

Usage

  •  Clean error handling
  •  No exceptions

 Returning Structs

Functions can return structs.


 

  •  Useful for grouped data

 Returning Slices

  •  Flexible
  • Common in APIs

 Returning Pointers

  •  Efficient for large data
  •  Avoids copying

 Early Return in Go

Early returns improve readability.

  •  Cleaner logic
  •  Fewer nested blocks

 Return vs Print

 Bad Practice

 Good Practice

  •  Reusable
  •  Testable

 Common Mistakes with Return Values

  •  Returning wrong type
  •  Forgetting return statement
  •  Ignoring errors
  •  Overusing named returns
  •  Mixing logic with printing

 Best Practices for Go Function Returns

  •  Keep return values minimal
  •  Use multiple returns wisely
  •  Always handle errors
  •  Prefer early returns
  •  Keep functions small

 Interview Questions: Go Function Returns

1. Can a Go function return multiple values?
Yes, Go supports multiple return values.

2. What is a named return?
A return variable declared in the function signature.

3. How are errors returned in Go?
As a second return value.

4. Can a function return a pointer?
Yes.

5. Should functions print or return values?
They should return values.


 Summary

  • Go functions can return single or multiple values
  •  Errors are returned, not thrown
  •  Named returns are supported
  • Structs, slices, and pointers can be returned
  • Clean return logic improves code quality

Mastering function returns in Go will help you write clean APIs, reusable functions, and production-ready code

You may also like...