在没有错误的情况下实现 `get_or_insert()`:不能多次将 `*self` 借用为可变的

时间:2021-07-05 19:26:17

标签: rust

我正在尝试为二叉搜索树实现 stroke-dashoffset 样式的方法。我似乎找不到让这个工作的技巧。以下失败。

我发布了一个 Accessing Child Component Instances & Child Elements,它以类似的方式重复了该问题。

get_or_insert()
struct Foo {
    data: Vec<i32>,
}

impl Foo {
    fn new() -> Self {
        Foo { data: vec![42; 5] }
    }

    fn get_mut(&mut self, index: usize) -> Option<&mut i32> {
        if index < self.data.len() {
            Some(&mut self.data[index])
        } else {
            None
        }
    }

    fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 { todo!() }
}

fn main() {
    let mut foo = Foo::new();
    let mut val = foo.get_or_insert(100, 88);
    *val = 42;
}
pub fn get_or_insert(&mut self, key: &K, value: V) -> &mut V {
    match self.get_mut(key) {
        Some(value) => value,
        None => {
            self.insert(key.clone(), value);
            self.get_mut(key).unwrap()
        }
    }
}

对获取值的第一次尝试进行范围界定也失败了。

error[E0499]: cannot borrow `self.data` as mutable more than once at a time
  --> src/main.rs:35:9
   |
29 |     fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 {
   |                      - let's call the lifetime of this reference `'1`
30 |         {
31 |             if let Some(value) = self.get_mut(index) {
   |                                  ---- first mutable borrow occurs here
32 |                 return value;
   |                        ----- returning this value requires that `*self` is borrowed for `'1`
...
35 |         self.data.extend_from_slice(vec![value; index].as_slice());
   |         ^^^^^^^^^ second mutable borrow occurs here

error[E0499]: cannot borrow `self.data` as mutable more than once at a time
  --> src/main.rs:36:14
   |
29 |     fn get_or_insert(&mut self, index: usize, value: i32) -> &mut i32 {
   |                      - let's call the lifetime of this reference `'1`
30 |         {
31 |             if let Some(value) = self.get_mut(index) {
   |                                  ---- first mutable borrow occurs here
32 |                 return value;
   |                        ----- returning this value requires that `*self` is borrowed for `'1`
...
36 |         &mut self.data[index]
   |              ^^^^^^^^^ second mutable borrow occurs here

我尝试了其他几种方法,但找不到有效的方法。我猜这是不可能的。有什么技巧可以让这样的功能发挥作用吗?

0 个答案:

没有答案