部分移动
在单个变量的 解构 中,按移动
和按引用
模式绑定可以同时使用。这样做会导致变量的部分移动,这意味着变量的一部分将被移动,而其他部分则保留。在这种情况下,父变量之后不能作为一个整体使用,但是仅被引用(而不是移动)的部分仍然可以使用。请注意,实现了 Drop
trait 的类型不能被部分移动,因为它的 drop
方法之后会将其作为一个整体使用。
fn main() { #[derive(Debug)] struct Person { name: String, age: Box<u8>, } // Error! cannot move out of a type which implements the `Drop` trait //impl Drop for Person { // fn drop(&mut self) { // println!("Dropping the person struct {:?}", self) // } //} // TODO ^ Try uncommenting these lines 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
复制数据而不会移动它。)