blob: d10eee549ed191d39eea2eb42a406807f895d11b [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 looks as it does in C or Java, except that the `(`)` are gone (they are not even optional) and the `{`}` are required.
.play flowcontrol/for.go
* For continued
As in C or Java, you can leave the pre and post statements empty.
.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
The `if` statement looks as it does in C or Java, except that the `(`)` are gone and the `{`}` are required.
(Sound familiar?)
.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 `main`'s call to `fmt.Println` 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]].