Recall & Review
beginner
What happens when a
return statement is executed inside a loop in Go?The function immediately stops executing and returns the specified value, exiting the loop and the function at once.
Click to reveal answer
beginner
Can code after a
return inside a loop run?No, once
return runs, the function ends immediately, so any code after it inside the loop or function does not run.Click to reveal answer
intermediate
Why might you use
return inside a loop in Go?To stop the function early when a condition is met, like finding a value or an error, avoiding unnecessary work.
Click to reveal answer
beginner
Example: What does this Go code print?
func findEven(nums []int) int {
for _, n := range nums {
if n%2 == 0 {
return n
}
}
return -1
}It returns the first even number found in the slice. If none found, it returns -1.
Click to reveal answer
intermediate
Is it good practice to use
return inside loops in Go?Yes, it is common and clear to return early from a function inside a loop when you have the result you want.
Click to reveal answer
What happens when a
return is executed inside a loop in Go?✗ Incorrect
In Go,
return immediately ends the function, so the loop and function stop.Can code after a
return inside a loop run?✗ Incorrect
Once
return runs, the function ends immediately, so no further code runs.Why use
return inside a loop?✗ Incorrect
Using
return inside a loop lets you stop the function early when you find what you need.What does this code return?
for i := 0; i < 5; i++ {
if i == 3 {
return i
}
}✗ Incorrect
When i equals 3, the function returns 3 and stops.
Is it okay to use
return inside loops in Go?✗ Incorrect
Returning inside loops is a common way to exit functions early in Go.
Explain what happens when a
return statement is used inside a loop in Go.Think about what happens to the function and loop when return runs.
You got /3 concepts.
Describe a situation where using
return inside a loop is helpful in Go programming.When might you want to stop searching or processing early?
You got /3 concepts.