if statements
An if
statement is the most basic form of logic in Go. An if
statement either will or will not run a block of code based on a Boolean expression. The notation looks like this: if <boolean expression> { <code
block> }
.
The Boolean expression can be simple code that results in a Boolean value. The code block can be any logic that you could also put in a function and are confined to the code block of that function. The code block runs when the Boolean expression is true. You can only use if
statements within the scope of a function. In Go, the concept of “function scope” refers to the visibility and accessibility of variables and statements within a function. .
Exercise 2.01 – a simple if statement
In this exercise, we’ll use an if
statement to control whether certain code will or will not run. We’ll define an int
value that will be hardcoded, but in a real-world application, this could be user input. We’ll then...