获取向量的最后一个元素并将其推送到同一个向量 [英] Get the last element of a vector and push it to the same vector

查看:56
本文介绍了获取向量的最后一个元素并将其推送到同一个向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做什么:

enum Test {
    Value1,
    Value2,
    Value3
}

fn main() {
    let mut test_vec: Vec<Test> = Vec::new();
    test_vec.push(Test::Value2);

    if let Some(last) = test_vec.last() {
        test_vec.push(*last);
    }
    //Wanted output: vector with [Test::Value2, Test::Value2]
}

我知道当我调用 last() 时,它会返回 Option<&Test>所以它会借用 test_vec 直到 if-let 块的结尾.

I understand that when I call last(), it will return Option<&Test> So it will borrow the test_vec till the end of the if-let block.

我尝试了以下方法但没有成功:

I tried the following without success:

if let Some(last) = test_vec.last().map(|v| v.clone()) {
    test_vec.push(*last);
}

//and

let last = test_vec.last().unwrap().clone();
test_vec.push(*last);

推荐答案

当试图找出借用检查器抱怨的原因时,识别所涉及的类型会很有用.

When trying to figure out why the borrow checker complains it can be useful to identify the types involved.

如果您输入:

let _: () = test_vec.last().map(|v| v.clone());

您收到一个错误,抱怨 ()core::option::Option<&Test> 不是同一类型.

you get an error complaining that () and core::option::Option<&Test> are not the same type.

这是怎么回事?简单地说,如果你克隆一个 &Test,你会得到一个 &Test,从而调用 .map(|v| v.clone())<Option<&Test> 上的/code> 给出了 Option<&Test>.显然,它还是借了.

What's going on? Very simply put, if you clone an &Test you get an &Test, thus calling .map(|v| v.clone()) on a Option<&Test> gives an Option<&Test>. Obviously, it still borrows.

如果您输入以下内容,则下次尝试时也会出现同样的问题:

The same problem occurs with your next attempt, if you type out:

let _: () = test_vec.last().unwrap().clone();

您收到一个错误,抱怨 ()&Test 不是同一类型.

you get an error complaining that () and &Test are not the same type.

通过在 Option<&Test> 上调用 unwrap,您会得到一个 &Test,然后将其克隆到 &测试.

By calling unwrap on an Option<&Test> you get an &Test which is then cloned into an &Test.

因此,问题在于缺乏取消引用.您需要提前取消引用,以避免在 Some(last):

So, the problem is a lack of dereferencing. You need to dereference earlier, to avoid borrowing test_vec in Some(last):

if let Some(last) = test_vec.last().map(|v| (*v).clone()) {
    test_vec.push(last);
}

当然,这是行不通的,因为Test 没有实现clone.一旦修复(通过#[derive(Clone)]),它就会编译.

of course, this does not work because Test does not implement clone. Once that is fixed (by #[derive(Clone)]), it compiles.

由于从引用中克隆是一种常见的需求,因此 Option(和 Iterator) 被称为 cloned:

Since cloning from references is such a common need, there is a dedicated method on Option (and Iterator) called cloned:

if let Some(last) = test_vec.last().cloned() {
    test_vec.push(last);
}

这篇关于获取向量的最后一个元素并将其推送到同一个向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆