Bird
Raised Fist0
Goprogramming~10 mins

Return inside loops in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Return inside loops
Start function
↓
Enter loop
↓
Check condition
Yes↓
Execute loop body
↓
Return encountered?
Yes→Exit function immediately
No↓
Next iteration
Back to Check condition↓
Exit loop
↓
Return at end of function
↓
End function
↩Back to Check condition
The function starts and enters a loop. Each iteration checks a condition. If a return statement runs inside the loop, the function exits immediately, skipping remaining iterations.
Execution Sample
Go
func findFirstEven(nums []int) int {
    for _, n := range nums {
        if n%2 == 0 {
            return n
        }
    }
    return -1
}
This function loops through numbers and returns the first even number it finds, stopping the loop immediately.
Execution Table
StepIterationCurrent number (n)Condition (n%2==0)ActionReturn Value
113falseContinue loopnone
227falseContinue loopnone
334trueReturn 4 and exit function4
💡 Return executed at iteration 3 when n=4, function exits immediately.
Variable Tracker
VariableStartAfter 1After 2After 3 (Return)
nundefined374
return valuenonenonenone4
Key Moments - 2 Insights
Why does the loop stop immediately when return is executed inside it?
Because return exits the entire function immediately, skipping all remaining loop iterations as shown in execution_table row 3.
What happens if no number satisfies the condition inside the loop?
The loop finishes all iterations without returning, then the function returns the value after the loop, here -1 (not shown in this trace).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'n' at step 2?
A4
B3
C7
Dnone
💡 Hint
Check the 'Current number (n)' column at step 2 in the execution_table.
At which iteration does the function return a value?
A3
B2
C1
DNever
💡 Hint
Look at the 'Return Value' column and find when it changes from 'none' to a number.
If the input slice had no even numbers, what would happen to the return value?
AReturn the first number anyway
BReturn -1 after the loop finishes
CReturn 0 immediately
DThe function would never return
💡 Hint
Refer to the code in execution_sample where return -1 is after the loop.
Concept Snapshot
Return inside loops in Go:
- A return inside a loop exits the entire function immediately.
- Loop stops running once return executes.
- If no return in loop, function can return after loop.
- Useful to find and return first matching item quickly.
Full Transcript
This example shows a Go function that loops through a list of numbers. Each number is checked if it is even. When the function finds the first even number, it returns that number immediately, stopping the loop and the function. If no even number is found, the function returns -1 after the loop finishes. The execution table traces each step, showing the current number, condition check, and when the return happens. The variable tracker shows how the variable 'n' changes each iteration and when the return value is set. Key moments clarify why the loop stops on return and what happens if no return occurs inside the loop. The quiz tests understanding of these steps and outcomes.

Practice

(1/5)
1.

What happens when you use return inside a for loop in Go?

easy
A. The function stops immediately and returns the value.
B. Only the current loop iteration stops, and the loop continues.
C. The loop skips the current iteration and moves to the next.
D. The loop runs forever without stopping.

Solution

  1. Step 1: Understand the role of return in functions

    In Go, return immediately ends the function and sends back a value.
  2. Step 2: Effect of return inside a loop

    When return is inside a loop, it stops the whole function, not just the loop.
  3. Final Answer:

    The function stops immediately and returns the value. -> Option A
  4. Quick Check:

    Return ends function, not just loop [OK]
Hint: Return inside loop ends function immediately [OK]
Common Mistakes:
  • Thinking return only stops the loop
  • Confusing return with break
  • Assuming loop continues after return
2.

Which of the following Go code snippets correctly uses return inside a for loop to return the first even number from a slice?

func firstEven(nums []int) int {
    for _, n := range nums {
        if n % 2 == 0 {
            // What goes here?
        }
    }
    return -1
}
easy
A. return n
B. break
C. continue
D. return nums

Solution

  1. Step 1: Identify what to return inside the loop

    The function should return the first even number found, which is n.
  2. Step 2: Use return to stop function and send back the number

    Using return n immediately ends the function and returns the even number.
  3. Final Answer:

    return n -> Option A
  4. Quick Check:

    Return value inside loop to stop function [OK]
Hint: Use return with value to exit function inside loop [OK]
Common Mistakes:
  • Using break instead of return
  • Using continue which skips iteration
  • Returning the whole slice instead of a number
3.

What is the output of this Go program?

package main
import "fmt"
func findFirstPositive(nums []int) int {
    for _, n := range nums {
        if n > 0 {
            return n
        }
    }
    return 0
}
func main() {
    fmt.Println(findFirstPositive([]int{-3, -2, 0, 5, 10}))
}
medium
A. 10
B. -3
C. 0
D. 5

Solution

  1. Step 1: Trace the loop over the slice

    The loop checks each number: -3 (not >0), -2 (not >0), 0 (not >0), 5 (>0).
  2. Step 2: Return the first positive number found

    When it reaches 5, it returns 5 immediately, ending the function.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Return stops at first positive number 5 [OK]
Hint: Return inside loop returns first matching value [OK]
Common Mistakes:
  • Assuming loop continues after return
  • Returning 0 instead of first positive
  • Confusing index with value
4.

Find the error in this Go function that tries to return the first negative number from a slice:

func firstNegative(nums []int) int {
    for _, n := range nums {
        if n < 0 {
            break
        }
    }
    return 0
}
medium
A. Returning 0 instead of -1 when no negative found
B. Missing else statement after if
C. Using break instead of return inside the loop
D. Loop variable should be index, not value

Solution

  1. Step 1: Understand break vs return inside loop

    Using break only stops the loop, but the function continues and returns 0.
  2. Step 2: Correct usage is return to stop function and return value

    To return the first negative number, use return n inside the if block.
  3. Final Answer:

    Using break instead of return inside the loop -> Option C
  4. Quick Check:

    Return ends function; break only stops loop [OK]
Hint: Use return, not break, to exit function inside loop [OK]
Common Mistakes:
  • Using break instead of return
  • Expecting break to return value
  • Not returning value inside loop
5.

You want to write a Go function that returns the first string in a slice that starts with the letter 'A'. If none is found, return "Not found". Which code correctly uses return inside the loop?

func findA(words []string) string {
    for _, w := range words {
        if len(w) > 0 && w[0] == 'A' {
            // What goes here?
        }
    }
    return "Not found"
}
hard
A. break
B. return w
C. continue
D. return words[0]

Solution

  1. Step 1: Identify the correct return value inside the loop

    The function should return the first word starting with 'A', which is w.
  2. Step 2: Use return to immediately end the function and return the word

    Using return w stops the function and returns the found word.
  3. Final Answer:

    return w -> Option B
  4. Quick Check:

    Return found word inside loop to stop function [OK]
Hint: Return matching item inside loop to stop function early [OK]
Common Mistakes:
  • Using break which only stops loop
  • Using continue which skips iteration
  • Returning wrong element like words[0]
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard