上篇文章探讨了struct的成员的所有权转移,struct允许部分成员转移所有权。那么另一个常用的类型Vec呢?是不允许的。下面代码无法编译:
fn main() {
let a = vec![Box::new(3), Box::new(4)];
let b = a[0];
}
提示如下错误:
cannot move out of index of `std::vec::Vec<std::boxed::Box<i32>>`
move occurs because value has type `std::boxed::Box<i32>`, which does not implement the `Copy` trait
同时编译器会提示考虑借用a[0]。因为这已经涉及到智能指针了,下次再学习更复杂的场景。