

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 3
click for more info
Not enough gems
Cost: 6 gems
1: Conditionals
incomplete
2: The Initial Statement of an If Block
incomplete
3: Switch
incomplete
4: Calculate Balance
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
An if conditional can have an "initial" statement. The variable(s) created in the initial statement are only defined within the scope of the if, else if, and else blocks.
if INITIAL_STATEMENT; CONDITION {
}
It has two valuable purposes:
if statementFor example, instead of writing:
length := getLength(email)
if length < 10 {
fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}
We can do:
if length := getLength(email); length < 10 {
fmt.Printf("Email must be at least 10 characters, is %d\n", length)
}
In the example above, length isn't available in the parent scope, which is nice because we don't need it there - we won't accidentally use it elsewhere in the function. It would still be available in any else if or else blocks attached to that if.