0
0
Goprogramming~10 mins

Return values in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Return values
Start function call
Execute function body
Return value(s)
Receive returned value(s)
Continue program
This flow shows how a function runs, sends back value(s), and the program uses them.
Execution Sample
Go
package main
import "fmt"
func add(a, b int) int {
    return a + b
}
func main() {
    fmt.Println(add(3, 4))
}
This code defines a function that adds two numbers and returns the sum, then prints it.
Execution Table
StepActionVariablesReturn ValueOutput
1Call add(3, 4)a=3, b=4
2Calculate a + ba=3, b=47
3Return 7 to callera=3, b=47
4Print returned value7
5Program ends
💡 Function returns value 7, printed by main, then program ends
Variable Tracker
VariableStartAfter Step 1After Step 2Final
a-333
b-444
return value-77
Key Moments - 2 Insights
Why do we see the return value only after the function finishes?
Because the function runs all its code first (see Step 2), then sends back the value (Step 3). The program waits for this before printing.
What happens if the function has no return statement?
The function returns nothing (void). In Go, if the function signature says it returns a value, it must have a return statement (not shown here).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the return value at Step 3?
A7
B3
C4
D0
💡 Hint
Check the 'Return Value' column at Step 3 in the execution table.
At which step does the program print the returned value?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Output' column in the execution table to find when printing happens.
If we change add(3, 4) to add(5, 6), what will be the return value at Step 3?
A7
B11
C9
D0
💡 Hint
Return value is sum of inputs a and b, see variable values in variable_tracker.
Concept Snapshot
func functionName(params) returnType {
    // code
    return value
}

- Function runs code then returns value.
- Caller receives and can use returned value.
- Return ends function execution.
Full Transcript
This example shows how a Go function returns a value. The function add takes two numbers, adds them, and returns the sum. The program calls add(3, 4), the function runs and returns 7. Then main prints 7. The execution table traces each step: calling the function, calculating sum, returning value, printing output, and ending. Variables a and b hold inputs, return value holds the sum. Beginners often wonder why return happens after all code runs; it does because return sends the final result back to the caller. If the function had no return, it would return nothing. Changing inputs changes the return value accordingly. This is the basic flow of return values in Go functions.