blob: 4adfb653886ff793363a2ded7a90c4f34f629f34 [file] [log] [blame]
Flow control statements: for, if, else, switch and defer
Learn how to control the flow of your code with conditionals, loops, switches and defers.
The Go Authors
https://golang.org
* For
Go has only one looping construct, the `for` loop.
The basic `for` loop has three components separated by semicolons:
- the init statement: executed before the first iteration
- the condition expression: evaluated before every iteration
- the post statement: executed at the end of every iteration
The init statement will often be a short variable declaration, and the
variables declared there are visible only in the scope of the `for`
statement.
The loop will stop iterating once the boolean condition evaluates to `false`.
_Note_: Unlike other languages like C, Java, or Javascript there are no parentheses
surrounding the three components of the `for` statement and the braces `{`}` are
always required.
.play flowcontrol/for.go
* For continued
The init and post statement are optional.
.play flowcontrol/for-continued.go
* For is Go's "while"
At that point you can drop the semicolons: C's `while` is spelled `for` in Go.
.play flowcontrol/for-is-gos-while.go
* Forever
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
.play flowcontrol/forever.go
* If
Go's `if` statements are like its `for` loops; the expression need not be
surrounded by parentheses `(`)` but the braces `{`}` are required.
.play flowcontrol/if.go
* If with a short statement
Like `for`, the `if` statement can start with a short statement to execute before the condition.
Variables declared by the statement are only in scope until the end of the `if`.
(Try using `v` in the last `return` statement.)
.play flowcontrol/if-with-a-short-statement.go
* If and else
Variables declared inside an `if` short statement are also available inside any
of the `else` blocks.
(Both calls to `pow` are executed and return before the call to `fmt.Println`
in `main` begins.)
.play flowcontrol/if-and-else.go
* Exercise: Loops and Functions
As a simple way to play with functions and loops, implement the square root function using Newton's method.
In this case, Newton's method is to approximate `Sqrt(x)` by picking a starting point _z_ and then repeating:
.image /content/img/newton.png
To begin with, just repeat that calculation 10 times and see how close you get to the answer for various values (1, 2, 3, ...).
Next, change the loop condition to stop once the value has stopped changing (or only changes by a very small delta). See if that's more or fewer iterations. How close are you to the [[https://golang.org/pkg/math/#Sqrt][math.Sqrt]]?
Hint: to declare and initialize a floating point value, give it floating point syntax or use a conversion:
z := float64(1)
z := 1.0
.play flowcontrol/exercise-loops-and-functions.go
* Switch
You probably knew what `switch` was going to look like.
A case body breaks automatically, unless it ends with a `fallthrough` statement.
.play flowcontrol/switch.go
* Switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
(For example,
switch i {
case 0:
case f():
}
does not call `f` if `i==0`.)
#appengine: *Note:* Time in the Go playground always appears to start at
#appengine: 2009-11-10 23:00:00 UTC, a value whose significance is left as an
#appengine: exercise for the reader.
.play flowcontrol/switch-evaluation-order.go
* Switch with no condition
Switch without a condition is the same as `switch`true`.
This construct can be a clean way to write long if-then-else chains.
.play flowcontrol/switch-with-no-condition.go
* Defer
A defer statement defers the execution of a function until the surrounding
function returns.
The deferred call's arguments are evaluated immediately, but the function call
is not executed until the surrounding function returns.
.play flowcontrol/defer.go
* Stacking defers
Deferred function calls are pushed onto a stack. When a function returns, its
deferred calls are executed in last-in-first-out order.
To learn more about defer statements read this
[[https://blog.golang.org/defer-panic-and-recover][blog post]].
.play flowcontrol/defer-multi.go
* Congratulations!
You finished this lesson!
You can go back to the list of [[/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]].