0
0
Goprogramming~5 mins

Break statement in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the break statement do in Go?
The break statement immediately stops the execution of the nearest enclosing loop or switch statement and exits it.
Click to reveal answer
beginner
In which Go control structures can you use the break statement?
You can use break inside for loops and switch statements to exit them early.
Click to reveal answer
intermediate
What happens if you use break inside a nested loop?
The break statement only exits the innermost loop where it is used, not all outer loops.
Click to reveal answer
advanced
How can you use break with labels in Go?
You can label loops and use break with the label name to exit an outer loop from inside an inner loop.
Click to reveal answer
beginner
Example: What will this code print?
for i := 1; i <= 5; i++ {
  if i == 3 {
    break
  }
  fmt.Println(i)
}
It will print:<br>1<br>2<br>Because when i becomes 3, the break stops the loop immediately.
Click to reveal answer
What does the break statement do inside a for loop in Go?
ADoes nothing special
BStops the loop immediately and exits it
CRestarts the loop from the beginning
DSkips the current iteration and continues
Can break be used to exit a switch statement in Go?
AYes, it exits the switch
BNo, it only works in loops
COnly if the switch is inside a loop
DOnly with labels
What happens if you use break inside an inner loop nested in an outer loop?
AOnly the inner loop stops
BBoth loops stop
COnly the outer loop stops
DNo loops stop
How do you break out of an outer loop from inside an inner loop in Go?
AYou cannot break outer loops
BUse <code>continue</code> with a label
CUse <code>return</code>
DUse <code>break</code> with a label
What will this code print?
for i := 0; i < 3; i++ {
  for j := 0; j < 3; j++ {
    if j == 1 {
      break
    }
    fmt.Print(j)
  }
  fmt.Println(i)
}
A0 0 1 2
B0 0 0
C00 01 02
D0 1 2
Explain how the break statement works in Go loops and switches.
Think about how to stop a repeating action early.
You got /3 concepts.
    Describe how to use labels with break to exit outer loops in Go.
    Labels help break out of nested loops.
    You got /3 concepts.