Video Coming Soon...
08: Flow Control: If
WARNING This exercise is in DRAFT status, so there may be errors. If you find any, please email me at help@learncodethehardway.com so I can fix them.
A program that only stores values and prints them out isn't very useful. We also need a way to make decisions in our code so we can alter what it does. Maybe we use some settings to change the output or need to abort if there's an error. The if-statement
does this by testing a bool
and running one block of code or another depending on whether the bool
is true
or false
.
true
/false
Tests
A true
/false
test is also called a "boolean test" or "boolean expression." A boolean test takes two variables and compares them to each other to produce a new true
/false
result. You can also do this with a variable and another value. This comparison is done using some form of "equality operator" like ==
or !=
between the two variables like this:
x := 10
y := 10
x == y
x != y
In this example I created two variables x
and y
and then tested if they were equal with ==
and not equal with !=
. You can also replace x
or y
with a number:
x == 1
y != 10
A comparison of 1 != 1
is going to be false
, and another with 1 == 1
is going to be true
.
You can then chain these comparisons together to test many of them at once. Take a look at this example:
x == 1 && y == 10
The &&
is the "and-operator" and it says, "if the test on the left of the &&
is true
AND the test on the right of the &&
is true
, this whole test is true
." You can also use the ||
(or) operator to compare two tests with OR logic:
x == 10 || y == 10
This says, "if the test on the left of the ||
is true
OR the test on the right of the ||
is true
then the whole test is true
."
You can also chain as many of these together as you want, but the more you create the harder it becomes to understand what the result will be. For example:
x == y && j == 10 || z == 100 && x == 1
After about 3 it becomes difficult to figure out, so it's better to create a variable for some of the parts that has an actual meaning:
can_move := x == y && j == 10
has_health := z == 100 && x == 1
can_move || has_health
Finally, all of these forms of "boolean tests" can go in an if-statement
to determin if a block of code should run or not.
All Boolean Test Operators
Here is a table of all operators you can use in boolean (true
/false
) tests:
Operator | Syntax | Explanation |
---|---|---|
&& | a && b | If a is true AND b is true then this is true . |
|| | a || b | If a is true OR b is true then this is true . |
! | !a | The inverse of a , so if a is false this makes it true. |
== | a == b | If a is equal to b then this is true . |
!= | a != b | If a IS NOT equal to b then this is true . |
() | (expr) | Just like in algebra in PEMDAS. |
< | a < b | If a is less than b then this is true . |
<= | a <= b | If a is less than OR EQUAL TO b then this is true . |
> | a > b | If a is greater than b then this is true . |
>= | a >= b | If a is greater than OR EQUAL TO b then this is true . |
You can use all of these anywhere that accepts a bool
as a result. That means other functions, variable assignments, return values, if
, for
, and switch
.
NOTE It will help to memorize these, but a good way to do that is to create a cheat sheet by hand. Write these out on a piece of paper manually then put it next to your computer while you code. This will let you look it up when you need it, and as you constantly look it up you "accidentally" memorize it.
Branches and Blocks
For an if-statement
to work you need two pieces of code to select from. Go separates these pieces of code using the {}
"block" syntax. Any code you place inside {
and }
will be executed when that boolean test is equal to true. For example:
if 1 == 1 {
fmt.Println("I am the true block.")
} else {
fmt.Println("I am the false block.")
}
This will run the first block and not the second. If you wrote if false
{` instead it would run the second block.
This is also called a "branch" because it's as if the code is structured like branches on a tree that the computer follows to perform it's processing.
The Code
Here's a simple piece of code to play with:
View Source file ex08/main.go Only
package main
import (
"fmt"
)
func main() {
sunshine := true
rain := false
if sunshine && !rain {
fmt.Println("I want to go outside to paint.")
} else if sunshine && rain {
fmt.Println("That's nice but I can't paint.")
} else if !sunshine && rain {
fmt.Println("It's really raining out.")
} else if !sunshine && !rain {
fmt.Println("I can go out, but there's no light.")
} else {
panic("The world ended.")
}
}
Type it in and let's break each new line down so you understand it.
The Breakdown
I'm not going to explain every line anymore, just the lines of code inside the main
function or ones that are interesting.
sunshine := true
-- Assigntrue
to a variable about the sunshine.rain := false
-- Assignfalse
to a variable about the rain.if sunshine && !rain {
-- Test if there's sunshine but not rain.fmt.Println("I want to go outside to paint.")
-- Print that I want to go outside.} else if sunshine && rain {
-- Test if there's sunshine and rain.fmt.Println("That's nice but I can't paint.")
-- Print that I can't go outside.} else if !sunshine && rain {
-- Test if there's not sunshine and it's raining.fmt.Println("It's really raining out.")
-- Print that's raining out.} else if !sunshine && !rain {
-- Test if there's not sunshine and not rain.fmt.Println("I can go out, but there's no light.")
-- Print that there's no good light for painting.} else {
-- Finally, if nothing else is valid then...panic("The world ended.")
-- Print that the world ended.}
-- This final}
end the wholeif-statement
.
The only new thing in this code is the if
, else
, and boolean logic I covered earlier. Make sure you understand this before continuing because it's use everywhere.
The Practice
- Break It -- You need to learn what error messages mean and what causes them, so break this code on purpose in as many ways as possible.
- Change It -- Try different combinations of
sunshine
andrain
to see what happens. Make sure you can explain why it happened as well. - Remake It -- Write up a description of the code, hide or delete this, then try to recreate it using the process from Exercise 04: How to Write Code. Try to do this from memory as much as possible.
Study Drills
- Try to cause the final
} else {
clause to trigger. Can you explain why you can or cannot make it run? - Write a whole new
if-statement
that uses 3 variables to make decisions. This could get really large so just do a fewif else
then have a finalelse
. - Create flash cards for the truth tables in
true/false Tests
and drill them in your spare time. Memorizing these will make it so you don't have to think about them when you use them.
Register for Learn Go the Hard Way
Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.