返回对现有矢量元素或新插入的元素的引用

时间:2019-02-12 18:01:13

标签: rust borrow-checker borrowing

struct Foo {
    a: Vec<i32>,
}

impl Foo {
    fn bar(&mut self) -> &i32 {
        if let Some(x) = self.a.iter().find(|i| **i == 0) {
            return x;
        }
        self.a.push(0);
        self.a.last().unwrap()
    }
}

Playground

此代码在语义上对我来说是正确的。它应该返回对向量中现有元素的引用,或者创建一个新元素并返回对其的引用。但是我收到以下错误:

error[E0502]: cannot borrow `self.a` as mutable because it is also borrowed as immutable
  --> src/lib.rs:10:9
   |
6  |     fn bar(&mut self) -> &i32 {
   |            - let's call the lifetime of this reference `'1`
7  |         if let Some(x) = self.a.iter().find(|i| **i == 0) {
   |                          ------ immutable borrow occurs here
8  |             return x;
   |                    - returning this value requires that `self.a` is borrowed for `'1`
9  |         }
10 |         self.a.push(0);
   |         ^^^^^^^^^^^^^^ mutable borrow occurs here

有没有办法使此代码编译?

0 个答案:

没有答案