如何从向量中克隆最后一个元素? [英] How to clone last element from vector?
问题描述
我正在尝试编写代码来获取某个向量的最后一个元素,并根据该元素执行不同的操作(包括向量的变异).
I'm trying to write code that gets the last element of some vector and do different actions (including mutation of the vector) depending on that element.
我是这样试的:
#[derive(Clone, PartialEq)]
enum ParseItem {
Start,
End,
}
let mut item_vec = vec![ParseItem::End];
loop {
let last_item = *item_vec.last().clone().unwrap();
match last_item {
ParseItem::End => item_vec.push(ParseItem::Start),
_ => break,
}
}
我收到以下错误:
错误:无法移出借来的内容
让 last_item = *item_vec.last().clone().unwrap();
error: cannot move out of borrowed content
let last_item = *item_vec.last().clone().unwrap();
我认为通过克隆item_vec.last()
,所有权问题会得到解决,但似乎没有.
I thought by cloning item_vec.last()
, the problems with ownership would be solved, but it seems not.
如果我用这样的整数向量尝试同样的事情:
If I try the same thing with a vector of integers like this:
let mut int_vec = vec![0];
loop {
let last_int = *int_vec.last().clone().unwrap();
match last_int {
0 => int_vec.push(1),
_ => break,
}
}
编译器不会抱怨借用.
为什么我的代码无法编译?
Why does my code fails to compile?
推荐答案
item_vec.last()
是一个 Option<&T>
.
item_vec.last().clone()
是另一个 Option<&T>
.这实际上执行了引用的浅副本.这意味着您实际上还没有修复任何东西!
item_vec.last().clone()
is another Option<&T>
. This actually performs a shallow copy of the reference. This means you haven't actually fixed anything!
直觉上,这是有道理的 - 克隆指针可以返回值类型以直接存储在堆栈上,但是 Option<&T>
不能em> 克隆 T
因为它无处可放.
Intuitively, this makes sense - cloning a pointer can return a value type to store directly on the stack, but a clone of an Option<&T>
can't clone the T
because it has nowhere to put it.
这是可行的,因为 Option
实际上在 &T
上调用了 clone
,所以 Option<&T>;
在 &&T
上调用 clone
,这意味着特征中的 &self
参数解析为 self = &T
.这意味着我们使用 impl
Clone
for &T
:
This works because an Option<T>
actually calls clone
on an &T
, so Option<&T>
calls clone
on an &&T
, which means the &self
parameter in the trait resolves to self = &T
. This means we use the impl
of Clone
for &T
:
impl<'a, T: ?Sized> Clone for &'a T {
/// Returns a shallow copy of the reference.
#[inline]
fn clone(&self) -> &'a T { *self }
}
*item_vec.last().clone().unwrap()
因此仍然是向量的借用.
*item_vec.last().clone().unwrap()
thus is still a borrow of the vector.
可以通过两种基本方式解决此问题.一种是使用 Option
's cloned
方法,克隆内部引用:
One can fix this in two basic ways. One is to use Option
's cloned
method, which clones the inner reference away:
item_vec.last().cloned().unwrap()
impl<'a, T: Clone> Option<&'a T> {
/// Maps an Option<&T> to an Option<T> by cloning the contents of the Option.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn cloned(self) -> Option<T> {
self.map(|t| t.clone())
}
}
另一种选择是解包
并且只then clone
引用,得到一个值:
The other option is to unwrap
and only then clone
the reference, to get a value out:
item_vec.last().unwrap().clone()
这篇关于如何从向量中克隆最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!