Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

字段访问表达式

Syntax
FieldExpressionExpression . IDENTIFIER

字段表达式是求值为结构体联合体字段位置的位置表达式

当操作数是可变的时,字段表达式也是可变的。

字段表达式的语法是一个表达式(称为容器操作数),然后是 .,最后是标识符

字段表达式后面不能跟括号括起来的逗号分隔的表达式列表,因为那会被解析为方法调用表达式。也就是说,它们不能是调用表达式的函数操作数。

Note

将字段表达式包装在括号表达式中以在调用表达式中使用它。

#![allow(unused)]
fn main() {
struct HoldsCallable<F: Fn()> { callable: F }
let holds_callable = HoldsCallable { callable: || () };

// Invalid: Parsed as calling the method "callable"
// holds_callable.callable();

// Valid
(holds_callable.callable)();
}

示例:

mystruct.myfield;
foo().x;
(Struct {a: 10, b: 20}).a;
(mystruct.function_field)() // Call expression containing a field expression

自动解引用

如果容器操作数的类型根据操作数是否可变实现 DerefDerefMut,则会根据需要自动解引用多次以使字段访问成为可能。此过程也简称为autoderef

借用

结构体或对结构体的引用的字段在借用时被视为单独的实体。如果结构体未实现 Drop 并且存储在局部变量中,这也适用于从其每个字段移出。如果通过 Box 以外的用户定义类型进行自动解引用,则也不适用。

#![allow(unused)]
fn main() {
struct A { f1: String, f2: String, f3: String }
let mut x: A;
x = A {
    f1: "f1".to_string(),
    f2: "f2".to_string(),
    f3: "f3".to_string()
};
let a: &mut String = &mut x.f1; // x.f1 borrowed mutably
let b: &String = &x.f2;         // x.f2 borrowed immutably
let c: &String = &x.f2;         // Can borrow again
let d: String = x.f3;           // Move out of x.f3
}