]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/expressions/field-expr.md
New upstream version 1.52.0~beta.3+dfsg1
[rustc.git] / src / doc / reference / src / expressions / field-expr.md
1 # Field access expressions
2
3 > **<sup>Syntax</sup>**\
4 > _FieldExpression_ :\
5 > &nbsp;&nbsp; [_Expression_] `.` [IDENTIFIER]
6
7 A _field expression_ consists of an expression followed by a single dot and an [identifier], when not immediately followed by a parenthesized expression-list (the latter is always a [method call expression]).
8 A field expression denotes a field of a [struct] or [union].
9 To call a function stored in a struct, parentheses are needed around the field expression.
10
11 <!-- ignore: needs lots of support code -->
12 ```rust,ignore
13 mystruct.myfield;
14 foo().x;
15 (Struct {a: 10, b: 20}).a;
16 mystruct.method(); // Method expression
17 (mystruct.function_field)() // Call expression containing a field expression
18 ```
19
20 A field access is a [place expression] referring to the location of that field.
21 When the subexpression is [mutable], the field expression is also mutable.
22
23 Also, if the type of the expression to the left of the dot is a pointer, it is automatically dereferenced as many times as necessary to make the field access possible.
24 In cases of ambiguity, we prefer fewer autoderefs to more.
25
26 Finally, the fields of a struct or a reference to a struct are treated as separate entities when borrowing.
27 If the struct does not implement [`Drop`](../special-types-and-traits.md#drop) and is stored in a local variable, this also applies to moving out of each of its fields.
28 This also does not apply if automatic dereferencing is done though user defined types other than [`Box`](../special-types-and-traits.html#boxt).
29
30 ```rust
31 struct A { f1: String, f2: String, f3: String }
32 let mut x: A;
33 # x = A {
34 # f1: "f1".to_string(),
35 # f2: "f2".to_string(),
36 # f3: "f3".to_string()
37 # };
38 let a: &mut String = &mut x.f1; // x.f1 borrowed mutably
39 let b: &String = &x.f2; // x.f2 borrowed immutably
40 let c: &String = &x.f2; // Can borrow again
41 let d: String = x.f3; // Move out of x.f3
42 ```
43
44 [_Expression_]: ../expressions.md
45 [IDENTIFIER]: ../identifiers.md
46 [method call expression]: method-call-expr.md
47 [struct]: ../items/structs.md
48 [union]: ../items/unions.md
49 [place expression]: ../expressions.md#place-expressions-and-value-expressions
50 [mutable]: ../expressions.md#mutability