Level: BeginnerInterview

Go Control Flow Questions: If, Switch and Loops (Part 3)

Updated 9 min read
Go Control Flow Questions featured image: if, switch and range cards

These Go control flow questions cover if, switch, for, range, labels and goto. Interviewers use them to test how you write everyday logic. We collected them from public interview lists, coding tests and forum threads. Then we grouped them by statement, so you can revise one idea at a time.

This post is questions only, so answer each one in your own words first. When you need help, read Go conditional statements and Go for loops. Also, finish Part 2 on data types before this one.

How to Use These Go Control Flow Questions

Answer each question out loud in two or three sentences. Then write a tiny program for any question you are unsure about, because control flow is easy to test. Finally, try the scenario questions, since they show how you choose between statements.

The table below shows each section and how many questions it has.

SectionWhat it testsQuestions
if and elseConditions, init statements and errors15
switchExpression, tagless and type switches17
for loopsThree forms of the single loop15
rangeSlices, maps, strings, channels and ints16
break, continue, labels, gotoLeaving and skipping loops13
Clean codeEarly return and nesting12
Code readingPredict the output4
Go Control Flow Questions diagram showing six question areas from if and else to clean control flow
Go control flow questions grouped into six areas: if and else, switch, for loops, range, labels and jumps, and clean control flow.

Go Control Flow Questions on if and else

Before you answer, study Go conditional statements. These Go control flow questions look easy, so interviewers listen for detail.

  1. How do you write an if statement in Go, and why are there no brackets around the condition?
  2. Why must the opening brace sit on the same line as if?
  3. What is an if statement with a short init statement?
  4. What is the scope of a variable declared in the if init statement?
  5. Can you use that variable inside the else block as well?
  6. Why does Go reject a non bool value in a condition, such as an int?
  7. How do you write the common if err != nil check, and why is it so frequent?
  8. When should you use else if instead of a switch?
  9. Is there a ternary operator in Go, so how do you write a short choice?
  10. How do you compare two strings in a condition, for example ignoring case?
  11. What does “happy path on the left” mean for Go code?
  12. Can an if statement check a map lookup and its ok value at once?
  13. How do you combine conditions safely so a nil pointer is never read?
  14. Scenario: when a function has five nested if blocks, how would you flatten it?
  15. Scenario: when an error check is missing after a file open, what bug can follow in production?

Go Control Flow Questions on switch

Switch in Go has several features that other languages lack. So many Go control flow questions ask how it differs from C or Java.

  1. How is a Go switch different from a switch in C or Java?
  2. Why do you not need break at the end of each case?
  3. What does fallthrough do, and when would you use it?
  4. Can fallthrough be used in the last case or in a type switch?
  5. How do you list several values in one case, such as Saturday and Sunday?
  6. What is a tagless switch, and when is it cleaner than if and else?
  7. Can a switch have an init statement like an if statement?
  8. Where can the default case appear, and does its position matter?
  9. Can case values be expressions instead of constants?
  10. What happens if two case values are the same constant?
  11. What is a type switch, and how does it differ from a value switch?
  12. How do you get the typed value inside a type switch case?
  13. What happens when you use break inside a switch inside a for loop?
  14. How would you break out of the loop instead of only the switch?
  15. Can you switch on a struct value or an interface value?
  16. Scenario: when a payment status switch misses a new status, how would you catch it early?
  17. Scenario: when a long if and else chain checks one variable, how would you refactor it?

Go Control Flow Questions on for Loops

Before you answer, study Go for loops with examples. Go has only one loop keyword, so these Go control flow questions test all its forms.

  1. Why does Go have only for, and no while or do while keyword?
  2. What are the three forms of a for loop in Go?
  3. How do you write a while style loop with for?
  4. How do you write an infinite loop, and how do you leave it?
  5. Can you leave out the init or post statement in a for loop?
  6. What is the scope of the loop variable declared in the header?
  7. How did loop variable behaviour change in Go 1.22?
  8. Why did the old behaviour cause bugs with closures and goroutines?
  9. How do you loop backwards over a slice?
  10. How do you loop with two variables, such as i going up and j going down?
  11. Can you change the loop variable inside the loop body, and is it wise?
  12. How would you write a loop that runs at most three retries?
  13. What is the cost of calling len in the loop condition?
  14. Scenario: when a loop never ends in production, what would you check first?
  15. Scenario: when old code copies the loop variable before a goroutine, is that copy still needed?

Go Control Flow Questions on range

Range works with many types, so interviewers ask what it returns for each. Also, the newer forms of range are a good sign that you keep up with the language.

  1. What does range return for a slice or an array?
  2. What does range return for a map, and in what order?
  3. Why is map iteration order random in Go?
  4. What does range return for a string, and why is it a rune?
  5. How do you range over a channel, and when does the loop stop?
  6. How do you range over an integer, since Go 1.22?
  7. What are range over function iterators, added in Go 1.23?
  8. Does range copy the value of each element, and why does that matter?
  9. How do you change slice elements while you range over them?
  10. What happens if you append to a slice while you range over it?
  11. Can you delete map keys while you range over the map?
  12. How do you ignore the index or the value with the blank identifier?
  13. Is range over an array different from range over a pointer to an array?
  14. How would you print map keys in sorted order?
  15. Scenario: when a test passes locally but fails in CI because of map order, how would you fix it?
  16. Scenario: when updating structs inside a range loop has no effect, what is the cause?

Break, Continue, Labels and goto Questions

These statements are used less often. However, interviewers like them for tricky Go control flow questions with printed output.

  1. What is the difference between break and continue?
  2. What is a label, and how do you attach it to a loop?
  3. How does break with a label work in nested loops?
  4. How does continue with a label work in nested loops?
  5. Can a label be used with switch and select as well?
  6. Does Go have goto, and what are its rules?
  7. Why can goto not jump over a variable declaration?
  8. When, if ever, would you use goto in real code?
  9. What happens to deferred calls when you break out of a loop?
  10. How do you stop a loop early when a value is found?
  11. Can an unused label cause a compile error?
  12. Scenario: when you search a grid and want to stop at the first match, how would you exit both loops?
  13. Scenario: when a reviewer finds goto in new code, what would you suggest instead?

Clean Control Flow Questions

Good Go code is easy to read from top to bottom. So these Go control flow questions test style as much as syntax.

  1. What is an early return, and why do Go developers prefer it?
  2. How deep should nesting go before you refactor?
  3. When would you replace a long switch with a map of functions?
  4. How do guard clauses make error handling easier to read?
  5. Why should a function usually do one thing, especially with loops?
  6. How do you keep a loop body short when it grows large?
  7. When is it better to return from a loop than to use a flag variable?
  8. How would you write a retry loop with a delay between attempts?
  9. What does the select statement have in common with switch?
  10. How do you test every branch of an if or switch?
  11. Scenario: when a handler mixes validation, loops and database calls, how would you split it?
  12. Scenario: when a loop must stop on a timeout, which statement would you combine with it?

Code Reading Questions

Read each program and predict the output before you run it. Then explain the reason in plain words.

package main

import "fmt"

func main() {
	switch n := 2; n {
	case 1:
		fmt.Println("one")
	case 2:
		fmt.Println("two")
		fallthrough
	case 3:
		fmt.Println("three")
	default:
		fmt.Println("other")
	}
}
  1. Which lines does this program print?
  2. Why does the default case not run, even though fallthrough is used?

Here is the second program. This time, focus on labels and loop variables.

package main

import "fmt"

func main() {
outer:
	for i := 0; i < 3; i++ {
		for j := 0; j < 3; j++ {
			if j == 2 {
				continue outer
			}
			if i == 2 {
				break outer
			}
			fmt.Println(i, j)
		}
	}

	var funcs []func()
	for i := range 3 {
		funcs = append(funcs, func() { fmt.Print(i, " ") })
	}
	for _, f := range funcs {
		f()
	}
	fmt.Println()
}
  1. Which pairs of i and j does the first loop print?
  2. What do the saved functions print with Go 1.22 or newer, and what did older versions print?

Quick Revision Table for Go Control Flow

Use the table below as a final check. It lists what range gives you for each type.

Type in rangeFirst valueSecond value
Slice or arrayIndexCopy of the element
StringByte indexRune
MapKeyValue
ChannelReceived valueNot used
Integer n0 to n minus 1Not used

Also, many interviewers ask when switch is better than if. The diagram below compares them.

Go Control Flow Questions diagram showing a comparison of if and else with switch
if and else suits a few unrelated conditions, while switch suits many cases on one value or one type, and never needs break.

Official Resources

These official pages describe the rules behind these questions.

Quick Recap

  • These Go control flow questions cover if, switch, for, range, labels and clean code.
  • A Go switch never falls through unless you write fallthrough.
  • Go has one loop keyword with three forms.
  • Loop variables are new on each iteration since Go 1.22.
  • Range returns different values for slices, strings, maps, channels and integers.
  • Prefer early returns over deep nesting.

What’s Next?

By now, you have Go control flow questions for every statement, so you can answer with clear examples. So next, we will cover functions, closures, variadic functions and defer.

Next up: Go functions interview questions on closures and defer (Part 4)