Control Flow in Go
Control Flow is where your programs start to make choices and repeat work.
In this chapter, you will:
- choose between paths with
if,elseandswitch - repeat work with
forandrange - name groups of steps as functions, and reuse them
What each lesson covers:
- Conditional Statements: Make choices in Go with if, if with a short statement, else, else if chains, nested if, switch, multiple cases, fallthrough and the expressionless switch.
- Loops: Repeat work in Go with the for loop in its three forms, walk through arrays, slices, strings, maps and channels with range, and control loops with break, continue, labels and goto.
- Functions: Declare and call Go functions, pass parameters, return one, many or named values, and use variadic functions, closures, higher-order functions, recursion, defer and scope.
This chapter has 3 lessons. Plan on about 75 minutes, with 12 exercises to check what you learned. Every example is real Go code: change it, run it again and compare the output, which is the fastest way to learn how each feature behaves.
Simple lesson: finish this chapter and your programs can decide, repeat and reuse.
Lessons in this section
- Conditional Statements
Make choices in Go with if, if with a short statement, else, else if chains, nested if, switch, multiple cases, fallthrough and the expressionless switch.
- Write if statements, with and without a short statement
- Build else and else if chains in the right order
- Nest if statements and keep them readable
- Use switch, multiple cases, fallthrough and expressionless switch
- Loops
Repeat work in Go with the for loop in its three forms, walk through arrays, slices, strings, maps and channels with range, and control loops with break, continue, labels and goto.
- Explain why loops are used
- Write counting, condition-only and infinite for loops
- Use range with arrays, slices, strings, maps and channels
- Control loops with break, continue and labels
- Functions
Declare and call Go functions, pass parameters, return one, many or named values, and use variadic functions, closures, higher-order functions, recursion, defer and scope.
- Declare and call functions with parameters
- Return single, multiple and named values
- Write variadic and anonymous functions and closures
- Pass functions to functions and return them