部分移动
在单个变量的解构中,可以同时使用 by-move
和 by-reference
模式绑定。这样做会导致变量的部分移动,这意味着变量的一部分将被移动,而其他部分则保持不变。在这种情况下,父变量之后不能再作为一个整体使用,但是仅被引用(而没有移动)的部分仍然可以使用。
fn main() { #[derive(Debug)] struct Person { name: String, age: Box<u8>, } let person = Person { name: String::from("Alice"), age: Box::new(20), }; // `name` is moved out of person, but `age` is referenced let Person { name, ref age } = person; println!("The person's age is {}", age); println!("The person's name is {}", name); // Error! borrow of partially moved value: `person` partial move occurs //println!("The person struct is {:?}", person); // `person` cannot be used but `person.age` can be used as it is not moved println!("The person's age from person struct is {}", person.age); }
(在这个例子中,我们将 age
变量存储在堆上来说明部分移动:删除上面代码中的 ref
会导致错误,因为 person.age
的所有权将移动到变量 age
。如果 Person.age
存储在栈上,则不需要 ref
,因为 age
的定义会从 person.age
复制数据而不会移动它。)