vector - 如何从可变向量中克隆最后一个元素,然后将值推送到 Rust 中的向量?

标签 vector rust borrowing

如何从 可变 向量中克隆最后一个元素,然后将值推送到 Rust 中的向量?

fn ElementsFromPoint(&self, ...) -> Vec<Root<Element>> {

    let mut elements: Vec<Root<Element>> = self.elements_from_point(point).iter()
        .map(|&untrusted_node_addr| {...}).collect();     

    let last_element = elements.last().clone().unwrap(); // elements.last() is Option<&Root<Element>>
    if let Some(root_element) = self.GetDocumentElement() { //self.GetDocumentElement() is Option<Root<Element>>
        if *last_element != root_element {
            elements.push(root_element);
        }
    }


    elements
}

错误是

2620:17: 2620:25 error: cannot borrow `elements` as mutable because it is also borrowed as immutable [E0502]
2620                 elements.push(root_element);
                     ^~~~~~~~
2617:28: 2617:36 note: previous borrow of `elements` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `elements` until the borrow ends
2617         let last_element = elements.last().clone().unwrap();
                                ^~~~~~~~
2626:6: 2626:6 note: previous borrow ends here
2590     fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<Root<Element>> {
                                                         ...
2626     }
                                                             ^
2625:9: 2625:17 error: cannot move out of `elements` because it is borrowed [E0505]
2625         elements
             ^~~~~~~~
2617:28: 2617:36 note: borrow of `elements` occurs here
2617         let last_element = elements.last().clone().unwrap();

我已阅读 this并尝试过

let last_element = elements.last().unwrap().clone();

还有

let last_element = elements.last().map(|t| t.clone()).unwrap();

但还是失败了。

还有.cloned()未针对 Root<T> 实现还没有。

有没有办法从 可变 向量中克隆最后一个元素,然后将值推送到 Rust 中的向量?或者我应该实现 Cloned特质优先?

最佳答案

试试这个

fn ElementsFromPoint(&self, ...) -> Vec<Root<Element>> {

    let mut elements: Vec<Root<Element>> = self.elements_from_point(point).iter()
        .map(|&untrusted_node_addr| {...}).collect();


    if let Some(root_element) = self.GetDocumentElement() {
        if {
            match elements.last() {
                Some(last_element) => *last_element != root_element,
                None => true
            }                
        } {
            elements.push(root_element);
        }
    }

    elements
}

关于vector - 如何从可变向量中克隆最后一个元素,然后将值推送到 Rust 中的向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36027235/

相关文章:

c++ - 如何声明线程 vector

c++ - 通过在 C++ 中单独直接访问其迭代器来删除容器的元素

ios - 将带有绑定(bind) Rust 二进制文件的 Flutter 应用程序发布到 AppStore 时出现问题

pointers - 为什么通过原始指针修改可变引用的值不会违反 Rust 的别名规则?

rust - 如何避免 filter_map() 在 Rust 中给出错误 "returns a value referencing data owned by the current function"?

c++ - 自动 vector 边界检查而不会使我的程序崩溃

c++ - 构造不同类型的 C++ vector 数组

rust - 如何将GBK编码的文件读入String?

rust - 如何在泛型中使用 `Num::one()`?

rust - 特征的生命周期作为返回值