|
| 1 | +# Control structures |
| 2 | + |
| 3 | +## Conditionals |
| 4 | + |
| 5 | +We've seen `if` pass by a few times already. To recap, braces are |
| 6 | +compulsory, an optional `else` clause can be appended, and multiple |
| 7 | +`if`/`else` constructs can be chained together: |
| 8 | + |
| 9 | + if false { |
| 10 | + std::io::println("that's odd"); |
| 11 | + } else if true { |
| 12 | + std::io::println("right"); |
| 13 | + } else { |
| 14 | + std::io::println("neither true nor false"); |
| 15 | + } |
| 16 | + |
| 17 | +The condition given to an `if` construct *must* be of type boolean (no |
| 18 | +implicit conversion happens). If the arms return a value, this value |
| 19 | +must be of the same type for every arm in which control reaches the |
| 20 | +end of the block: |
| 21 | + |
| 22 | + fn signum(x: int) -> int { |
| 23 | + if x < 0 { -1 } |
| 24 | + else if x > 0 { 1 } |
| 25 | + else { ret 0; } |
| 26 | + } |
| 27 | + |
| 28 | +The `ret` (return) and its semicolon could have been left out without |
| 29 | +changing the meaning of this function, but it illustrates that you |
| 30 | +will not get a type error in this case, although the last arm doesn't |
| 31 | +have type `int`, because control doesn't reach the end of that arm |
| 32 | +(`ret` is jumping out of the function). |
| 33 | + |
| 34 | +## Pattern matching |
| 35 | + |
| 36 | +Rust's `alt` construct is a generalized, cleaned-up version of C's |
| 37 | +`switch` construct. You provide it with a value and a number of arms, |
| 38 | +each labelled with a pattern, and it will execute the arm that matches |
| 39 | +the value. |
| 40 | + |
| 41 | + alt my_number { |
| 42 | + 0 { std::io::println("zero"); } |
| 43 | + 1 | 2 { std::io::println("one or two"); } |
| 44 | + 3 to 10 { std::io::println("three to ten"); } |
| 45 | + _ { std::io::println("something else"); } |
| 46 | + } |
| 47 | + |
| 48 | +There is no 'falling through' between arms, as in C—only one arm is |
| 49 | +executed, and it doesn't have to explicitly `break` out of the |
| 50 | +construct when it is finished. |
| 51 | + |
| 52 | +The part to the left of each arm is called the pattern. Literals are |
| 53 | +valid patterns, and will match only their own value. The pipe operator |
| 54 | +(`|`) can be used to assign multiple patterns to a single arm. Ranges |
| 55 | +of numeric literal patterns can be expressed with `to`. The underscore |
| 56 | +(`_`) is a wildcard pattern that matches everything. |
| 57 | + |
| 58 | +If the arm with the wildcard pattern was left off in the above |
| 59 | +example, running it on a number greater than ten (or negative) would |
| 60 | +cause a run-time failure. When no arm matches, `alt` constructs do not |
| 61 | +silently fall through—they blow up instead. |
| 62 | + |
| 63 | +A powerful application of pattern matching is *destructuring*, where |
| 64 | +you use the matching to get at the contents of data types. Remember |
| 65 | +that `(float, float)` is a tuple of two floats: |
| 66 | + |
| 67 | + fn angle(vec: (float, float)) -> float { |
| 68 | + alt vec { |
| 69 | + (0f, y) when y < 0f { 1.5 * std::math::pi } |
| 70 | + (0f, y) { 0.5 * std::math::pi } |
| 71 | + (x, y) { std::math::atan(y / x) } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | +A variable name in a pattern matches everything, *and* binds that name |
| 76 | +to the value of the matched thing inside of the arm block. Thus, `(0f, |
| 77 | +y)` matches any tuple whose first element is zero, and binds `y` to |
| 78 | +the second element. `(x, y)` matches any tuple, and binds both |
| 79 | +elements to a variable. |
| 80 | + |
| 81 | +Any `alt` arm can have a guard clause (written `when EXPR`), which is |
| 82 | +an expression of type `bool` that determines, after the pattern is |
| 83 | +found to match, whether the arm is taken or not. The variables bound |
| 84 | +by the pattern are available in this guard expression. |
| 85 | + |
| 86 | +## Destructuring let |
| 87 | + |
| 88 | +To a limited extent, it is possible to use destructuring patterns when |
| 89 | +declaring a variable with `let`. For example, you can say this to |
| 90 | +extract the fields from a tuple: |
| 91 | + |
| 92 | + let (a, b) = get_tuple_of_two_ints(); |
| 93 | + |
| 94 | +This will introduce two new variables, `a` and `b`, bound to the |
| 95 | +content of the tuple. |
| 96 | + |
| 97 | +You may only use irrevocable patterns in let bindings, though. Things |
| 98 | +like literals, which only match a specific value, are not allowed. |
| 99 | + |
| 100 | +## Loops |
| 101 | + |
| 102 | +`while` produces a loop that runs as long as its given condition |
| 103 | +(which must have type `bool`) evaluates to true. Inside a loop, the |
| 104 | +keyword `break` can be used to abort the loop, and `cont` can be used |
| 105 | +to abort the current iteration and continue with the next. |
| 106 | + |
| 107 | + let x = 5; |
| 108 | + while true { |
| 109 | + x += x - 3; |
| 110 | + if x % 5 == 0 { break; } |
| 111 | + std::io::println(std::int::str(x)); |
| 112 | + } |
| 113 | + |
| 114 | +This code prints out a weird sequence of numbers and stops as soon as |
| 115 | +it finds one that can be divided by five. |
| 116 | + |
| 117 | +When iterating over a vector, use `for` instead. |
| 118 | + |
| 119 | + for elt in ["red", "green", "blue"] { |
| 120 | + std::io::println(elt); |
| 121 | + } |
| 122 | + |
| 123 | +This will go over each element in the given vector (a three-element |
| 124 | +vector of strings, in this case), and repeatedly execute the body with |
| 125 | +`elt` bound to the current element. You may add an optional type |
| 126 | +declaration (`elt: str`) for the iteration variable if you want. |
| 127 | + |
| 128 | +For more involved iteration, such as going over the elements of a hash |
| 129 | +table, Rust uses higher-order functions. We'll come back to those in a |
| 130 | +moment. |
| 131 | + |
| 132 | +## Failure |
| 133 | + |
| 134 | +The `fail` keyword causes the current [task][tasks] to fail. You use |
| 135 | +it to indicate unexpected failure, much like you'd use `exit(1)` in a |
| 136 | +C program, except that in Rust, it is possible for other tasks to |
| 137 | +handle the failure, allowing the program to continue running. |
| 138 | + |
| 139 | +`fail` takes an optional argument, which must have type `str`. Trying |
| 140 | +to access a vector out of bounds, or running a pattern match with no |
| 141 | +matching clauses, both result in the equivalent of a `fail`. |
| 142 | + |
| 143 | +[tasks]: FIXME |
| 144 | + |
| 145 | +## Logging |
| 146 | + |
| 147 | +Rust has a built-in logging mechanism, using the `log` statement. |
| 148 | +Logging is polymorphic—any type of value can be logged, and the |
| 149 | +runtime will do its best to output a textual representation of the |
| 150 | +value. |
| 151 | + |
| 152 | + log "hi"; |
| 153 | + log (1, [2.5, -1.8]); |
| 154 | + |
| 155 | +By default, you *will not* see the output of your log statements. The |
| 156 | +environment variable `RUST_LOG` controls which log statements actually |
| 157 | +get output. It can contain a comma-separated list of paths for modules |
| 158 | +that should be logged. For example, running `rustc` with |
| 159 | +`RUST_LOG=rustc::front::attr` will turn on logging in its attribute |
| 160 | +parser. If you compile a program `foo.rs`, you can set `RUST_LOG` to |
| 161 | +`foo` to enable its logging. |
| 162 | + |
| 163 | +Turned-off `log` statements impose minimal overhead on the code that |
| 164 | +contains them, so except in code that needs to be really, really fast, |
| 165 | +you should feel free to scatter around debug logging statements, and |
| 166 | +leave them in. |
| 167 | + |
| 168 | +For interactive debugging, you often want unconditional logging. For |
| 169 | +this, use `log_err` instead of `log` [FIXME better name]. |
0 commit comments