Text file tour/flowcontrol.article

     1  Flow control statements: for, if, else, switch and defer
     2  Learn how to control the flow of your code with conditionals, loops, switches and defers.
     3  
     4  The Go Authors
     5  https://golang.org
     6  
     7  * For
     8  
     9  Go has only one looping construct, the `for` loop.
    10  
    11  The basic `for` loop has three components separated by semicolons:
    12  
    13  - the init statement: executed before the first iteration
    14  - the condition expression: evaluated before every iteration
    15  - the post statement: executed at the end of every iteration
    16  
    17  The init statement will often be a short variable declaration, and the
    18  variables declared there are visible only in the scope of the `for`
    19  statement.
    20  
    21  The loop will stop iterating once the boolean condition evaluates to `false`.
    22  
    23  *Note:* Unlike other languages like C, Java, or JavaScript there are no parentheses
    24  surrounding the three components of the `for` statement and the braces `{`}` are
    25  always required.
    26  
    27  .play flowcontrol/for.go
    28  
    29  * For continued
    30  
    31  The init and post statements are optional.
    32  
    33  .play flowcontrol/for-continued.go
    34  
    35  * For is Go's "while"
    36  
    37  At that point you can drop the semicolons: C's `while` is spelled `for` in Go.
    38  
    39  .play flowcontrol/for-is-gos-while.go
    40  
    41  * Forever
    42  
    43  If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
    44  
    45  .play flowcontrol/forever.go
    46  
    47  * If
    48  
    49  Go's `if` statements are like its `for` loops; the expression need not be
    50  surrounded by parentheses `(`)` but the braces `{`}` are required.
    51  
    52  .play flowcontrol/if.go
    53  
    54  * If with a short statement
    55  
    56  Like `for`, the `if` statement can start with a short statement to execute before the condition.
    57  
    58  Variables declared by the statement are only in scope until the end of the `if`.
    59  
    60  (Try using `v` in the last `return` statement.)
    61  
    62  .play flowcontrol/if-with-a-short-statement.go
    63  
    64  * If and else
    65  
    66  Variables declared inside an `if` short statement are also available inside any
    67  of the `else` blocks.
    68  
    69  (Both calls to `pow` return their results before the call to `fmt.Println`
    70  in `main` begins.)
    71  
    72  .play flowcontrol/if-and-else.go
    73  
    74  * Exercise: Loops and Functions
    75  
    76  As a way to play with functions and loops, let's implement a square root function: given a number x, we want to find the number z for which z² is most nearly x.
    77  
    78  Computers typically compute the square root of x using a loop.
    79  Starting with some guess z, we can adjust z based on how close z² is to x,
    80  producing a better guess:
    81  
    82  	z -= (z*z - x) / (2*z)
    83  
    84  Repeating this adjustment makes the guess better and better
    85  until we reach an answer that is as close to the actual square root as can be.
    86  
    87  Implement this in the `func`Sqrt` provided.
    88  A decent starting guess for z is 1, no matter what the input.
    89  To begin with, repeat the calculation 10 times and print each z along the way.
    90  See how close you get to the answer for various values of x (1, 2, 3, ...)
    91  and how quickly the guess improves.
    92  
    93  Hint: To declare and initialize a floating point value,
    94  give it floating point syntax or use a conversion:
    95  
    96  	z := 1.0
    97  	z := float64(1)
    98  
    99  Next, change the loop condition to stop once the value has stopped
   100  changing (or only changes by a very small amount).
   101  See if that's more or fewer than 10 iterations.
   102  Try other initial guesses for z, like x, or x/2.
   103  How close are your function's results to the [[/pkg/math/#Sqrt][math.Sqrt]] in the standard library?
   104  
   105  (*Note:* If you are interested in the details of the algorithm, the z² − x above
   106  is how far away z² is from where it needs to be (x), and the division by 2z is the derivative
   107  of z², to scale how much we adjust z by how quickly z² is changing.
   108  This general approach is called [[https://en.wikipedia.org/wiki/Newton%27s_method][Newton's method]].
   109  It works well for many functions but especially well for square root.)
   110  
   111  .play flowcontrol/exercise-loops-and-functions.go
   112  
   113  * Switch
   114  
   115  A `switch` statement is a shorter way to write a sequence of `if`-`else` statements.
   116  It runs the first case whose value is equal to the condition expression.
   117  
   118  Go's switch is like the one in C, C++, Java, JavaScript, and PHP,
   119  except that Go only runs the selected case, not all the cases that follow.
   120  In effect, the `break` statement that is needed at the end of each case in those
   121  languages is provided automatically in Go.
   122  Another important difference is that Go's switch cases need not
   123  be constants, and the values involved need not be integers.
   124  
   125  .play flowcontrol/switch.go
   126  
   127  * Switch evaluation order
   128  
   129  Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
   130  
   131  (For example,
   132  
   133  	switch i {
   134  	case 0:
   135  	case f():
   136  	}
   137  
   138  does not call `f` if `i==0`.)
   139  
   140  #appengine: *Note:* Time in the Go playground always appears to start at
   141  #appengine: 2009-11-10 23:00:00 UTC, a value whose significance is left as an
   142  #appengine: exercise for the reader.
   143  
   144  .play flowcontrol/switch-evaluation-order.go
   145  
   146  * Switch with no condition
   147  
   148  Switch without a condition is the same as `switch`true`.
   149  
   150  This construct can be a clean way to write long if-then-else chains.
   151  
   152  .play flowcontrol/switch-with-no-condition.go
   153  
   154  * Defer
   155  
   156  A defer statement defers the execution of a function until the surrounding
   157  function returns.
   158  
   159  The deferred call's arguments are evaluated immediately, but the function call
   160  is not executed until the surrounding function returns.
   161  
   162  .play flowcontrol/defer.go
   163  
   164  * Stacking defers
   165  
   166  Deferred function calls are pushed onto a stack. When a function returns, its
   167  deferred calls are executed in last-in-first-out order.
   168  
   169  To learn more about defer statements read this
   170  [[/blog/defer-panic-and-recover][blog post]].
   171  
   172  .play flowcontrol/defer-multi.go
   173  
   174  * Congratulations!
   175  
   176  You finished this lesson!
   177  
   178  You can go back to the list of [[/tour/list][modules]] to find what to learn next, or continue with the [[javascript:click('.next-page')][next lesson]].
   179  

View as plain text