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