Coding/Learn/go/go functions and multiple returns
Go Foundational Course
01.Introduction, Toolchain & Package main
02.Variables, Zero Values, Constants & iota
03.Control Flow: If with Init Statements & Switch
04.The Unified For Loop & Range Iteration
05.Functions, Multiple Return Values & Named Returns
06.Arrays vs Slices: Dynamic Memory & Headers
07.Maps: Key-Value Hash Tables & Safe Access
08.Pointers & Value vs Pointer Semantics
09.Structs, Receiver Methods & Composition
10.Implicit Interfaces & Duck Typing with Typesafety
11.Explicit Error Handling, Wrapping & Inspection
12.Defer, Panic & Recover: Resource Cleanup
13.Strings, Runes & UTF-8 Encoding Internals
14.Goroutines & The M:N Work-Stealing Scheduler
15.Channels: CSP Concurrency & Pipelines
16.Select Statement, Non-Blocking IO & Timeouts
17.Mutexes, RWMutex & Atomic Primitives
18.Context Propagation, Cancellation & Deadlines
19.JSON Serialization, Tags & net/http Routing
20.Capstone: High-Performance Concurrent Microservice Engine
Course Certificate0%

Complete all lessons to earn

LearnFunctions, Multiple Return Values & Named Returns
5 / 20 0%
Lesson 05 of 20
6 mins read

Functions, Multiple Return Values & Named Returns

PreviousNext Lesson
In Plain English

In Go, functions are first-class citizens that can return multiple values natively. This enables Go's signature error handling pattern (result, err := fn()) without exceptions. Named return values act as pre-declared variables inside the function body.

The Mental Model

"A Go function is like a vending machine with two drop slots: one slot drops your cold soda can (the result), and the other drops your receipt or change (the status/error)."

Deep Dive: How It Works

Multiple Returns: func divide(a, b float64) (float64, error) returns data and error together.

Blank Identifier (_): Discards return values you do not need: val, _ := compute().

Variadic Parameters: func sum(nums ...int) accepts variable numbers of arguments.

Syntax Blueprint

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("division by zero")
    }
    return a / b, nil
}

Function signature returning tuple of float64 result and error interface.

PointCore Rules to Remember

Point star
Native Tuples: Returns multiple distinct types without creating wrapper DTO objects.
Point star
First-Class Functions: Functions can be assigned to variables, passed as callbacks, or returned as closures.
Point star
Clean Signatures: Parameters of identical type can share a single type annotation: func add(a, b int).

Common Beginner Traps & How to Fix Them

Mistake:Using "naked returns" (return without arguments) in large functions with named returns.

Why it happens: Named returns allow bare return statements, but in large functions it severely impairs readability.

How to fix: Always explicitly specify return values in non-trivial functions: return val, nil.

Pro Tip: Always place error as the last return value in multi-return functions following standard Go conventions.

Live Interactive Example

Hit Run Code to see it live
Safe Division with Multiple Returns
Go 1.22 / Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Output Console
Click "Run Code" to view the rendered output.
How it works: safeDivide returns 5.0 and nil error, confirming successful computation.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Calculate Dimensions and Area

  • PointWrite a function "rectStats(w, h float64) (area, perimeter float64)" that returns width*height and 2*(width+height).
  • PointCall rectStats(5, 3) and print "Area: %.1f, Perimeter: %.1f\n".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates