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