]> git.lizzy.rs Git - rust.git/blob - src/doc/reference/src/expressions.md
statements and expressions
[rust.git] / src / doc / reference / src / expressions.md
1 # Expressions
2
3 An expression may have two roles: it always produces a *value*, and it may have
4 *effects* (otherwise known as "side effects"). An expression *evaluates to* a
5 value, and has effects during *evaluation*. Many expressions contain
6 sub-expressions (operands). The meaning of each kind of expression dictates
7 several things:
8
9 * Whether or not to evaluate the sub-expressions when evaluating the expression
10 * The order in which to evaluate the sub-expressions
11 * How to combine the sub-expressions' values to obtain the value of the expression
12
13 In this way, the structure of expressions dictates the structure of execution.
14 Blocks are just another kind of expression, so blocks, statements, expressions,
15 and blocks again can recursively nest inside each other to an arbitrary depth.
16
17 ### Lvalues, rvalues and temporaries
18
19 Expressions are divided into two main categories: _lvalues_ and _rvalues_.
20 Likewise within each expression, sub-expressions may occur in _lvalue context_
21 or _rvalue context_. The evaluation of an expression depends both on its own
22 category and the context it occurs within.
23
24 An lvalue is an expression that represents a memory location. These expressions
25 are [paths](#path-expressions) (which refer to local variables, function and
26 method arguments, or static variables), dereferences (`*expr`), [indexing
27 expressions](#index-expressions) (`expr[expr]`), and [field
28 references](#field-expressions) (`expr.f`). All other expressions are rvalues.
29
30 The left operand of an [assignment](#assignment-expressions) or
31 [compound-assignment](#compound-assignment-expressions) expression is
32 an lvalue context, as is the single operand of a unary
33 [borrow](#unary-operator-expressions). The discriminant or subject of
34 a [match expression](#match-expressions) may be an lvalue context, if
35 ref bindings are made, but is otherwise an rvalue context. All other
36 expression contexts are rvalue contexts.
37
38 When an lvalue is evaluated in an _lvalue context_, it denotes a memory
39 location; when evaluated in an _rvalue context_, it denotes the value held _in_
40 that memory location.
41
42 #### Temporary lifetimes
43
44 When an rvalue is used in an lvalue context, a temporary un-named
45 lvalue is created and used instead. The lifetime of temporary values
46 is typically the innermost enclosing statement; the tail expression of
47 a block is considered part of the statement that encloses the block.
48
49 When a temporary rvalue is being created that is assigned into a `let`
50 declaration, however, the temporary is created with the lifetime of
51 the enclosing block instead, as using the enclosing statement (the
52 `let` declaration) would be a guaranteed error (since a pointer to the
53 temporary would be stored into a variable, but the temporary would be
54 freed before the variable could be used). The compiler uses simple
55 syntactic rules to decide which values are being assigned into a `let`
56 binding, and therefore deserve a longer temporary lifetime.
57
58 Here are some examples:
59
60 - `let x = foo(&temp())`. The expression `temp()` is an rvalue. As it
61   is being borrowed, a temporary is created which will be freed after
62   the innermost enclosing statement (the `let` declaration, in this case).
63 - `let x = temp().foo()`. This is the same as the previous example,
64   except that the value of `temp()` is being borrowed via autoref on a
65   method-call. Here we are assuming that `foo()` is an `&self` method
66   defined in some trait, say `Foo`. In other words, the expression
67   `temp().foo()` is equivalent to `Foo::foo(&temp())`.
68 - `let x = &temp()`. Here, the same temporary is being assigned into
69   `x`, rather than being passed as a parameter, and hence the
70   temporary's lifetime is considered to be the enclosing block.
71 - `let x = SomeStruct { foo: &temp() }`. As in the previous case, the
72   temporary is assigned into a struct which is then assigned into a
73   binding, and hence it is given the lifetime of the enclosing block.
74 - `let x = [ &temp() ]`. As in the previous case, the
75   temporary is assigned into an array which is then assigned into a
76   binding, and hence it is given the lifetime of the enclosing block.
77 - `let ref x = temp()`. In this case, the temporary is created using a ref binding,
78   but the result is the same: the lifetime is extended to the enclosing block.
79
80 ### Moved and copied types
81
82 When a [local variable](variables.html) is used as an
83 [rvalue](expressions.html#lvalues-rvalues-and-temporaries), the variable will
84 be copied if its type implements `Copy`. All others are moved.
85
86 ## Literal expressions
87
88 A _literal expression_ consists of one of the [literal](tokens.md#literals) forms
89 described earlier. It directly describes a number, character, string, boolean
90 value, or the unit value.
91
92 ```text
93 ();        // unit type
94 "hello";   // string type
95 '5';       // character type
96 5;         // integer type
97 ```
98
99 ## Path expressions
100
101 A [path](paths.html) used as an expression context denotes either a local
102 variable or an item. Path expressions are
103 [lvalues](expressions.html#lvalues-rvalues-and-temporaries).
104
105 ## Tuple expressions
106
107 Tuples are written by enclosing zero or more comma-separated expressions in
108 parentheses. They are used to create [tuple-typed](types.html#tuple-types)
109 values.
110
111 ```{.tuple}
112 (0.0, 4.5);
113 ("a", 4usize, true);
114 ```
115
116 You can disambiguate a single-element tuple from a value in parentheses with a
117 comma:
118
119 ```
120 (0,); // single-element tuple
121 (0); // zero in parentheses
122 ```
123
124 ## Struct expressions
125
126 There are several forms of struct expressions. A _struct expression_
127 consists of the [path](#paths) of a [struct item](items.html#structs), followed
128 by a brace-enclosed list of zero or more comma-separated name-value pairs,
129 providing the field values of a new instance of the struct. A field name can be
130 any identifier, and is separated from its value expression by a colon.  The
131 location denoted by a struct field is mutable if and only if the enclosing
132 struct is mutable.
133
134 A _tuple struct expression_ consists of the [path](#paths) of a [struct
135 item](items.html#structs), followed by a parenthesized list of one or more
136 comma-separated expressions (in other words, the path of a struct item followed
137 by a tuple expression). The struct item must be a tuple struct item.
138
139 A _unit-like struct expression_ consists only of the [path](#paths) of a
140 [struct item](items.html#structs).
141
142 The following are examples of struct expressions:
143
144 ```
145 # struct Point { x: f64, y: f64 }
146 # struct NothingInMe { }
147 # struct TuplePoint(f64, f64);
148 # mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
149 # struct Cookie; fn some_fn<T>(t: T) {}
150 Point {x: 10.0, y: 20.0};
151 NothingInMe {};
152 TuplePoint(10.0, 20.0);
153 let u = game::User {name: "Joe", age: 35, score: 100_000};
154 some_fn::<Cookie>(Cookie);
155 ```
156
157 A struct expression forms a new value of the named struct type. Note
158 that for a given *unit-like* struct type, this will always be the same
159 value.
160
161 A struct expression can terminate with the syntax `..` followed by an
162 expression to denote a functional update. The expression following `..` (the
163 base) must have the same struct type as the new struct type being formed.
164 The entire expression denotes the result of constructing a new struct (with
165 the same type as the base expression) with the given values for the fields that
166 were explicitly specified and the values in the base expression for all other
167 fields.
168
169 ```
170 # struct Point3d { x: i32, y: i32, z: i32 }
171 let base = Point3d {x: 1, y: 2, z: 3};
172 Point3d {y: 0, z: 10, .. base};
173 ```
174
175 #### Struct field init shorthand
176
177 When initializing a data structure (struct, enum, union) with named fields,
178 it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.
179 This allows a compact syntax with less duplication.
180
181 Example:
182
183 ```
184 # struct Point3d { x: i32, y: i32, z: i32 }
185 # let x = 0;
186 # let y_value = 0;
187 # let z = 0;
188 Point3d { x: x, y: y_value, z: z };
189 Point3d { x, y: y_value, z };
190 ```
191
192 ## Block expressions
193
194 A _block expression_ is similar to a module in terms of the declarations that
195 are possible. Each block conceptually introduces a new namespace scope. Use
196 items can bring new names into scopes and declared items are in scope for only
197 the block itself.
198
199 A block will execute each statement sequentially, and then execute the
200 expression (if given). If the block ends in a statement, its value is `()`:
201
202 ```
203 let x: () = { println!("Hello."); };
204 ```
205
206 If it ends in an expression, its value and type are that of the expression:
207
208 ```
209 let x: i32 = { println!("Hello."); 5 };
210
211 assert_eq!(5, x);
212 ```
213
214 ## Method-call expressions
215
216 A _method call_ consists of an expression followed by a single dot, an
217 identifier, and a parenthesized expression-list. Method calls are resolved to
218 methods on specific traits, either statically dispatching to a method if the
219 exact `self`-type of the left-hand-side is known, or dynamically dispatching if
220 the left-hand-side expression is an indirect [trait object](trait-objects.html).
221
222 ## Field expressions
223
224 A _field expression_ consists of an expression followed by a single dot and an
225 identifier, when not immediately followed by a parenthesized expression-list
226 (the latter is a [method call expression](#method-call-expressions)). A field
227 expression denotes a field of a [struct](types.html#struct-types).
228
229 ```{.ignore .field}
230 mystruct.myfield;
231 foo().x;
232 (Struct {a: 10, b: 20}).a;
233 ```
234
235 A field access is an [lvalue](expressions.html#lvalues-rvalues-and-temporaries)
236 referring to the value of that field. When the type providing the field
237 inherits mutability, it can be [assigned](#assignment-expressions) to.
238
239 Also, if the type of the expression to the left of the dot is a
240 pointer, it is automatically dereferenced as many times as necessary
241 to make the field access possible. In cases of ambiguity, we prefer
242 fewer autoderefs to more.
243
244 ## Array expressions
245
246 An [array](types.html#array-and-slice-types) _expression_ is written by
247 enclosing zero or more comma-separated expressions of uniform type in square
248 brackets.
249
250 In the `[expr ';' expr]` form, the expression after the `';'` must be a
251 constant expression that can be evaluated at compile time, such as a
252 [literal](tokens.html#literals) or a [static item](items.html#static-items).
253
254 ```
255 [1, 2, 3, 4];
256 ["a", "b", "c", "d"];
257 [0; 128];              // array with 128 zeros
258 [0u8, 0u8, 0u8, 0u8];
259 ```
260
261 ## Index expressions
262
263 [Array](types.html#array-and-slice-types)-typed expressions can be indexed by
264 writing a square-bracket-enclosed expression (the index) after them. When the
265 array is mutable, the resulting
266 [lvalue](expressions.html#lvalues-rvalues-and-temporaries) can be assigned to.
267
268 Indices are zero-based, and may be of any integral type. Vector access is
269 bounds-checked at compile-time for constant arrays being accessed with a
270 constant index value.  Otherwise a check will be performed at run-time that
271 will put the thread in a _panicked state_ if it fails.
272
273 ```{should-fail}
274 ([1, 2, 3, 4])[0];
275
276 let x = (["a", "b"])[10]; // compiler error: const index-expr is out of bounds
277
278 let n = 10;
279 let y = (["a", "b"])[n]; // panics
280
281 let arr = ["a", "b"];
282 arr[10]; // panics
283 ```
284
285 Also, if the type of the expression to the left of the brackets is a
286 pointer, it is automatically dereferenced as many times as necessary
287 to make the indexing possible. In cases of ambiguity, we prefer fewer
288 autoderefs to more.
289
290 ## Range expressions
291
292 The `..` operator will construct an object of one of the `std::ops::Range` variants.
293
294 ```
295 1..2;   // std::ops::Range
296 3..;    // std::ops::RangeFrom
297 ..4;    // std::ops::RangeTo
298 ..;     // std::ops::RangeFull
299 ```
300
301 The following expressions are equivalent.
302
303 ```
304 let x = std::ops::Range {start: 0, end: 10};
305 let y = 0..10;
306
307 assert_eq!(x, y);
308 ```
309
310 Similarly, the `...` operator will construct an object of one of the
311 `std::ops::RangeInclusive` variants.
312
313 ```
314 # #![feature(inclusive_range_syntax)]
315 1...2;   // std::ops::RangeInclusive
316 ...4;    // std::ops::RangeToInclusive
317 ```
318
319 The following expressions are equivalent.
320
321 ```
322 # #![feature(inclusive_range_syntax, inclusive_range)]
323 let x = std::ops::RangeInclusive::NonEmpty {start: 0, end: 10};
324 let y = 0...10;
325
326 assert_eq!(x, y);
327 ```
328
329 ## Unary operator expressions
330
331 Rust defines the following unary operators. With the exception of `?`, they are
332 all written as prefix operators, before the expression they apply to.
333
334 * `-`
335   : Negation. Signed integer types and floating-point types support negation. It
336     is an error to apply negation to unsigned types; for example, the compiler
337     rejects `-1u32`.
338 * `*`
339   : Dereference. When applied to a [pointer](types.html#pointer-types) it
340     denotes the pointed-to location. For pointers to mutable locations, the
341     resulting [lvalue](expressions.html#lvalues-rvalues-and-temporaries) can be
342     assigned to.  On non-pointer types, it calls the `deref` method of the
343     `std::ops::Deref` trait, or the `deref_mut` method of the
344     `std::ops::DerefMut` trait (if implemented by the type and required for an
345     outer expression that will or could mutate the dereference), and produces
346     the result of dereferencing the `&` or `&mut` borrowed pointer returned
347     from the overload method.
348 * `!`
349   : Logical negation. On the boolean type, this flips between `true` and
350     `false`. On integer types, this inverts the individual bits in the
351     two's complement representation of the value.
352 * `&` and `&mut`
353   : Borrowing. When applied to an lvalue, these operators produce a
354     reference (pointer) to the lvalue. The lvalue is also placed into
355     a borrowed state for the duration of the reference. For a shared
356     borrow (`&`), this implies that the lvalue may not be mutated, but
357     it may be read or shared again. For a mutable borrow (`&mut`), the
358     lvalue may not be accessed in any way until the borrow expires.
359     If the `&` or `&mut` operators are applied to an rvalue, a
360     temporary value is created; the lifetime of this temporary value
361     is defined by [syntactic rules](#temporary-lifetimes).
362 * `?`
363   : Propagating errors if applied to `Err(_)` and unwrapping if
364     applied to `Ok(_)`. Only works on the `Result<T, E>` type,
365     and written in postfix notation.
366
367 ## Binary operator expressions
368
369 Binary operators expressions are given in terms of [operator
370 precedence](#operator-precedence).
371
372 ### Arithmetic operators
373
374 Binary arithmetic expressions are syntactic sugar for calls to built-in traits,
375 defined in the `std::ops` module of the `std` library. This means that
376 arithmetic operators can be overridden for user-defined types. The default
377 meaning of the operators on standard types is given here.
378
379 * `+`
380   : Addition and array/string concatenation.
381     Calls the `add` method on the `std::ops::Add` trait.
382 * `-`
383   : Subtraction.
384     Calls the `sub` method on the `std::ops::Sub` trait.
385 * `*`
386   : Multiplication.
387     Calls the `mul` method on the `std::ops::Mul` trait.
388 * `/`
389   : Quotient.
390     Calls the `div` method on the `std::ops::Div` trait.
391 * `%`
392   : Remainder.
393     Calls the `rem` method on the `std::ops::Rem` trait.
394
395 ### Bitwise operators
396
397 Like the [arithmetic operators](#arithmetic-operators), bitwise operators are
398 syntactic sugar for calls to methods of built-in traits. This means that
399 bitwise operators can be overridden for user-defined types. The default
400 meaning of the operators on standard types is given here. Bitwise `&`, `|` and
401 `^` applied to boolean arguments are equivalent to logical `&&`, `||` and `!=`
402 evaluated in non-lazy fashion.
403
404 * `&`
405   : Bitwise AND.
406     Calls the `bitand` method of the `std::ops::BitAnd` trait.
407 * `|`
408   : Bitwise inclusive OR.
409     Calls the `bitor` method of the `std::ops::BitOr` trait.
410 * `^`
411   : Bitwise exclusive OR.
412     Calls the `bitxor` method of the `std::ops::BitXor` trait.
413 * `<<`
414   : Left shift.
415     Calls the `shl` method of the `std::ops::Shl` trait.
416 * `>>`
417   : Right shift (arithmetic).
418     Calls the `shr` method of the `std::ops::Shr` trait.
419
420 ### Lazy boolean operators
421
422 The operators `||` and `&&` may be applied to operands of boolean type. The
423 `||` operator denotes logical 'or', and the `&&` operator denotes logical
424 'and'. They differ from `|` and `&` in that the right-hand operand is only
425 evaluated when the left-hand operand does not already determine the result of
426 the expression. That is, `||` only evaluates its right-hand operand when the
427 left-hand operand evaluates to `false`, and `&&` only when it evaluates to
428 `true`.
429
430 ### Comparison operators
431
432 Comparison operators are, like the [arithmetic
433 operators](#arithmetic-operators), and [bitwise operators](#bitwise-operators),
434 syntactic sugar for calls to built-in traits. This means that comparison
435 operators can be overridden for user-defined types. The default meaning of the
436 operators on standard types is given here.
437
438 * `==`
439   : Equal to.
440     Calls the `eq` method on the `std::cmp::PartialEq` trait.
441 * `!=`
442   : Unequal to.
443     Calls the `ne` method on the `std::cmp::PartialEq` trait.
444 * `<`
445   : Less than.
446     Calls the `lt` method on the `std::cmp::PartialOrd` trait.
447 * `>`
448   : Greater than.
449     Calls the `gt` method on the `std::cmp::PartialOrd` trait.
450 * `<=`
451   : Less than or equal.
452     Calls the `le` method on the `std::cmp::PartialOrd` trait.
453 * `>=`
454   : Greater than or equal.
455     Calls the `ge` method on the `std::cmp::PartialOrd` trait.
456
457 ### Type cast expressions
458
459 A type cast expression is denoted with the binary operator `as`.
460
461 Executing an `as` expression casts the value on the left-hand side to the type
462 on the right-hand side.
463
464 An example of an `as` expression:
465
466 ```
467 # fn sum(values: &[f64]) -> f64 { 0.0 }
468 # fn len(values: &[f64]) -> i32 { 0 }
469
470 fn average(values: &[f64]) -> f64 {
471     let sum: f64 = sum(values);
472     let size: f64 = len(values) as f64;
473     sum / size
474 }
475 ```
476
477 Some of the conversions which can be done through the `as` operator
478 can also be done implicitly at various points in the program, such as
479 argument passing and assignment to a `let` binding with an explicit
480 type. Implicit conversions are limited to "harmless" conversions that
481 do not lose information and which have minimal or no risk of
482 surprising side-effects on the dynamic execution semantics.
483
484 ### Assignment expressions
485
486 An _assignment expression_ consists of an
487 [lvalue](expressions.html#lvalues-rvalues-and-temporaries) expression followed
488 by an equals sign (`=`) and an
489 [rvalue](expressions.html#lvalues-rvalues-and-temporaries) expression.
490
491 Evaluating an assignment expression [either copies or
492 moves](#moved-and-copied-types) its right-hand operand to its left-hand
493 operand.
494
495 ```
496 # let mut x = 0;
497 # let y = 0;
498 x = y;
499 ```
500
501 ### Compound assignment expressions
502
503 The `+`, `-`, `*`, `/`, `%`, `&`, `|`, `^`, `<<`, and `>>` operators may be
504 composed with the `=` operator. The expression `lval OP= val` is equivalent to
505 `lval = lval OP val`. For example, `x = x + 1` may be written as `x += 1`.
506
507 Any such expression always has the [`unit`](#tuple-types) type.
508
509 ### Operator precedence
510
511 The precedence of Rust binary operators is ordered as follows, going from
512 strong to weak:
513
514 ```{.text .precedence}
515 as :
516 * / %
517 + -
518 << >>
519 &
520 ^
521 |
522 == != < > <= >=
523 &&
524 ||
525 .. ...
526 <-
527 =
528 ```
529
530 Operators at the same precedence level are evaluated left-to-right. [Unary
531 operators](#unary-operator-expressions) have the same precedence level and are
532 stronger than any of the binary operators.
533
534 ## Grouped expressions
535
536 An expression enclosed in parentheses evaluates to the result of the enclosed
537 expression. Parentheses can be used to explicitly specify evaluation order
538 within an expression.
539
540 An example of a parenthesized expression:
541
542 ```
543 let x: i32 = (2 + 3) * 4;
544 ```
545
546
547 ## Call expressions
548
549 A _call expression_ invokes a function, providing zero or more input variables
550 and an optional location to move the function's output into. If the function
551 eventually returns, then the expression completes.
552
553 Some examples of call expressions:
554
555 ```
556 # fn add(x: i32, y: i32) -> i32 { 0 }
557
558 let x: i32 = add(1i32, 2i32);
559 let pi: Result<f32, _> = "3.14".parse();
560 ```
561
562 ## Lambda expressions
563
564 A _lambda expression_ (sometimes called an "anonymous function expression")
565 defines a function and denotes it as a value, in a single expression. A lambda
566 expression is a pipe-symbol-delimited (`|`) list of identifiers followed by an
567 expression.
568
569 A lambda expression denotes a function that maps a list of parameters
570 (`ident_list`) onto the expression that follows the `ident_list`. The
571 identifiers in the `ident_list` are the parameters to the function. These
572 parameters' types need not be specified, as the compiler infers them from
573 context.
574
575 Lambda expressions are most useful when passing functions as arguments to other
576 functions, as an abbreviation for defining and capturing a separate function.
577
578 Significantly, lambda expressions _capture their environment_, which regular
579 [function definitions](items.html#functions) do not. The exact type of capture
580 depends on the [function type](types.html#function-types) inferred for the
581 lambda expression. In the simplest and least-expensive form (analogous to a
582 ```|| { }``` expression), the lambda expression captures its environment by
583 reference, effectively borrowing pointers to all outer variables mentioned
584 inside the function.  Alternately, the compiler may infer that a lambda
585 expression should copy or move values (depending on their type) from the
586 environment into the lambda expression's captured environment. A lambda can be
587 forced to capture its environment by moving values by prefixing it with the
588 `move` keyword.
589
590 In this example, we define a function `ten_times` that takes a higher-order
591 function argument, and we then call it with a lambda expression as an argument,
592 followed by a lambda expression that moves values from its environment.
593
594 ```
595 fn ten_times<F>(f: F) where F: Fn(i32) {
596     for index in 0..10 {
597         f(index);
598     }
599 }
600
601 ten_times(|j| println!("hello, {}", j));
602
603 let word = "konnichiwa".to_owned();
604 ten_times(move |j| println!("{}, {}", word, j));
605 ```
606
607 ## Infinite loops
608
609 A `loop` expression denotes an infinite loop.
610
611 A `loop` expression may optionally have a _label_. The label is written as
612 a lifetime preceding the loop expression, as in `'foo: loop{ }`. If a
613 label is present, then labeled `break` and `continue` expressions nested
614 within this loop may exit out of this loop or return control to its head.
615 See [break expressions](#break-expressions) and [continue
616 expressions](#continue-expressions).
617
618 ## `break` expressions
619
620 A `break` expression has an optional _label_. If the label is absent, then
621 executing a `break` expression immediately terminates the innermost loop
622 enclosing it. It is only permitted in the body of a loop. If the label is
623 present, then `break 'foo` terminates the loop with label `'foo`, which need not
624 be the innermost label enclosing the `break` expression, but must enclose it.
625
626 ## `continue` expressions
627
628 A `continue` expression has an optional _label_. If the label is absent, then
629 executing a `continue` expression immediately terminates the current iteration
630 of the innermost loop enclosing it, returning control to the loop *head*. In
631 the case of a `while` loop, the head is the conditional expression controlling
632 the loop. In the case of a `for` loop, the head is the call-expression
633 controlling the loop. If the label is present, then `continue 'foo` returns
634 control to the head of the loop with label `'foo`, which need not be the
635 innermost label enclosing the `continue` expression, but must enclose it.
636
637 A `continue` expression is only permitted in the body of a loop.
638
639 ## `while` loops
640
641 A `while` loop begins by evaluating the boolean loop conditional expression.
642 If the loop conditional expression evaluates to `true`, the loop body block
643 executes and control returns to the loop conditional expression. If the loop
644 conditional expression evaluates to `false`, the `while` expression completes.
645
646 An example:
647
648 ```
649 let mut i = 0;
650
651 while i < 10 {
652     println!("hello");
653     i = i + 1;
654 }
655 ```
656
657 Like `loop` expressions, `while` loops can be controlled with `break` or
658 `continue`, and may optionally have a _label_. See [infinite
659 loops](#infinite-loops), [break expressions](#break-expressions), and
660 [continue expressions](#continue-expressions) for more information.
661
662 ## `for` expressions
663
664 A `for` expression is a syntactic construct for looping over elements provided
665 by an implementation of `std::iter::IntoIterator`.
666
667 An example of a `for` loop over the contents of an array:
668
669 ```
670 # type Foo = i32;
671 # fn bar(f: &Foo) { }
672 # let a = 0;
673 # let b = 0;
674 # let c = 0;
675
676 let v: &[Foo] = &[a, b, c];
677
678 for e in v {
679     bar(e);
680 }
681 ```
682
683 An example of a for loop over a series of integers:
684
685 ```
686 # fn bar(b:usize) { }
687 for i in 0..256 {
688     bar(i);
689 }
690 ```
691
692 Like `loop` expressions, `for` loops can be controlled with `break` or
693 `continue`, and may optionally have a _label_. See [infinite
694 loops](#infinite-loops), [break expressions](#break-expressions), and
695 [continue expressions](#continue-expressions) for more information.
696
697 ## `if` expressions
698
699 An `if` expression is a conditional branch in program control. The form of an
700 `if` expression is a condition expression, followed by a consequent block, any
701 number of `else if` conditions and blocks, and an optional trailing `else`
702 block. The condition expressions must have type `bool`. If a condition
703 expression evaluates to `true`, the consequent block is executed and any
704 subsequent `else if` or `else` block is skipped. If a condition expression
705 evaluates to `false`, the consequent block is skipped and any subsequent `else
706 if` condition is evaluated. If all `if` and `else if` conditions evaluate to
707 `false` then any `else` block is executed.
708
709 ## `match` expressions
710
711 A `match` expression branches on a *pattern*. The exact form of matching that
712 occurs depends on the pattern. Patterns consist of some combination of
713 literals, destructured arrays or enum constructors, structs and tuples,
714 variable binding specifications, wildcards (`..`), and placeholders (`_`). A
715 `match` expression has a *head expression*, which is the value to compare to
716 the patterns. The type of the patterns must equal the type of the head
717 expression.
718
719 In a pattern whose head expression has an `enum` type, a placeholder (`_`)
720 stands for a *single* data field, whereas a wildcard `..` stands for *all* the
721 fields of a particular variant.
722
723 A `match` behaves differently depending on whether or not the head expression
724 is an [lvalue or an rvalue](expressions.html#lvalues-rvalues-and-temporaries).
725 If the head expression is an rvalue, it is first evaluated into a temporary
726 location, and the resulting value is sequentially compared to the patterns in
727 the arms until a match is found. The first arm with a matching pattern is
728 chosen as the branch target of the `match`, any variables bound by the pattern
729 are assigned to local variables in the arm's block, and control enters the
730 block.
731
732 When the head expression is an lvalue, the match does not allocate a temporary
733 location (however, a by-value binding may copy or move from the lvalue). When
734 possible, it is preferable to match on lvalues, as the lifetime of these
735 matches inherits the lifetime of the lvalue, rather than being restricted to
736 the inside of the match.
737
738 An example of a `match` expression:
739
740 ```
741 let x = 1;
742
743 match x {
744     1 => println!("one"),
745     2 => println!("two"),
746     3 => println!("three"),
747     4 => println!("four"),
748     5 => println!("five"),
749     _ => println!("something else"),
750 }
751 ```
752
753 Patterns that bind variables default to binding to a copy or move of the
754 matched value (depending on the matched value's type). This can be changed to
755 bind to a reference by using the `ref` keyword, or to a mutable reference using
756 `ref mut`.
757
758 Subpatterns can also be bound to variables by the use of the syntax `variable @
759 subpattern`. For example:
760
761 ```
762 let x = 1;
763
764 match x {
765     e @ 1 ... 5 => println!("got a range element {}", e),
766     _ => println!("anything"),
767 }
768 ```
769
770 Patterns can also dereference pointers by using the `&`, `&mut` and `box`
771 symbols, as appropriate. For example, these two matches on `x: &i32` are
772 equivalent:
773
774 ```
775 # let x = &3;
776 let y = match *x { 0 => "zero", _ => "some" };
777 let z = match x { &0 => "zero", _ => "some" };
778
779 assert_eq!(y, z);
780 ```
781
782 Multiple match patterns may be joined with the `|` operator. A range of values
783 may be specified with `...`. For example:
784
785 ```
786 # let x = 2;
787
788 let message = match x {
789     0 | 1  => "not many",
790     2 ... 9 => "a few",
791     _      => "lots"
792 };
793 ```
794
795 Range patterns only work on scalar types (like integers and characters; not
796 like arrays and structs, which have sub-components). A range pattern may not
797 be a sub-range of another range pattern inside the same `match`.
798
799 Finally, match patterns can accept *pattern guards* to further refine the
800 criteria for matching a case. Pattern guards appear after the pattern and
801 consist of a bool-typed expression following the `if` keyword. A pattern guard
802 may refer to the variables bound within the pattern they follow.
803
804 ```
805 # let maybe_digit = Some(0);
806 # fn process_digit(i: i32) { }
807 # fn process_other(i: i32) { }
808
809 let message = match maybe_digit {
810     Some(x) if x < 10 => process_digit(x),
811     Some(x) => process_other(x),
812     None => panic!(),
813 };
814 ```
815
816 ## `if let` expressions
817
818 An `if let` expression is semantically identical to an `if` expression but in
819 place of a condition expression it expects a `let` statement with a refutable
820 pattern. If the value of the expression on the right hand side of the `let`
821 statement matches the pattern, the corresponding block will execute, otherwise
822 flow proceeds to the first `else` block that follows.
823
824 ```
825 let dish = ("Ham", "Eggs");
826
827 // this body will be skipped because the pattern is refuted
828 if let ("Bacon", b) = dish {
829     println!("Bacon is served with {}", b);
830 }
831
832 // this body will execute
833 if let ("Ham", b) = dish {
834     println!("Ham is served with {}", b);
835 }
836 ```
837
838 ## `while let` loops
839
840 A `while let` loop is semantically identical to a `while` loop but in place of
841 a condition expression it expects `let` statement with a refutable pattern. If
842 the value of the expression on the right hand side of the `let` statement
843 matches the pattern, the loop body block executes and control returns to the
844 pattern matching statement. Otherwise, the while expression completes.
845
846 ## `return` expressions
847
848 Return expressions are denoted with the keyword `return`. Evaluating a `return`
849 expression moves its argument into the designated output location for the
850 current function call, destroys the current function activation frame, and
851 transfers control to the caller frame.
852
853 An example of a `return` expression:
854
855 ```
856 fn max(a: i32, b: i32) -> i32 {
857     if a > b {
858         return a;
859     }
860     return b;
861 }
862 ```