]>
Commit | Line | Data |
---|---|---|
ea8adc8c XL |
1 | # Field access expressions |
2 | ||
3 | A _field expression_ consists of an expression followed by a single dot and an | |
4 | [identifier](identifiers.html), when not immediately followed by a | |
5 | parenthesized expression-list (the latter is always a [method call | |
6 | expression](expressions/method-call-expr.html)). A field expression denotes a field of a | |
7 | [struct](types.html#struct-types) or [union](items/unions.html). To call a | |
8 | function stored in a struct parentheses are needed around the field expression | |
9 | ||
10 | ```rust,ignore | |
11 | mystruct.myfield; | |
12 | foo().x; | |
13 | (Struct {a: 10, b: 20}).a; | |
14 | mystruct.method(); // Method expression | |
15 | (mystruct.function_field)() // Call expression containing a field expression | |
16 | ``` | |
17 | ||
18 | A field access is an [lvalue](expressions.html#lvalues-and-rvalues) referring | |
19 | to the location of that field. When the subexpression is | |
20 | [mutable](expressions.html#mutability), the field expression is also mutable. | |
21 | ||
22 | Also, if the type of the expression to the left of the dot is a pointer, it is | |
23 | automatically dereferenced as many times as necessary to make the field access | |
24 | possible. In cases of ambiguity, we prefer fewer autoderefs to more. | |
25 | ||
abe05a73 XL |
26 | Finally, the fields of a struct or a reference to a struct are treated as |
27 | separate entities when borrowing. If the struct does not implement | |
28 | [`Drop`](the-drop-trait.html) and is stored in a local variable, this also | |
29 | applies to moving out of each of its fields. This also does not apply if | |
30 | automatic dereferencing is done though user defined types. | |
ea8adc8c XL |
31 | |
32 | ```rust | |
abe05a73 XL |
33 | struct A { f1: String, f2: String, f3: String } |
34 | let mut x: A; | |
35 | # x = A { | |
ea8adc8c XL |
36 | # f1: "f1".to_string(), |
37 | # f2: "f2".to_string(), | |
38 | # f3: "f3".to_string() | |
39 | # }; | |
40 | let a: &mut String = &mut x.f1; // x.f1 borrowed mutably | |
41 | let b: &String = &x.f2; // x.f2 borrowed immutably | |
42 | let c: &String = &x.f2; // Can borrow again | |
43 | let d: String = x.f3; // Move out of x.f3 | |
44 | ``` |