如何在Vec上更新或插入?

问题描述 投票:5回答:2

我在Rust写一个数据结构。它包含一对Vec的键值对。当插入到结构中时,我需要找到匹配的键并更新键和值(实际上是子指针)。代码看起来有点像这样,其中pivotsref mutVec<Pivot>Pivot只是一个有两个字段的结构:

match pivots.iter_mut().find(|ref p| key <= p.min_key) { // first mutable borrow
    Some(ref mut pivot) => {
        // If there is one, insert into it and update the pivot key
        pivot.min_key = key;
        pivot.child.insert(key, value) // recursive call
    },
    // o/w, insert a new leaf at the end
    None => pivots.push(Pivot /* ... */) // second mutable borrow
}

但是有一个问题。尽管我没有在match的第二臂使用可变迭代器,但是借用检查器抱怨我“不能一次多次借用*pivots可变”。

这对我来说非常有意义,因为第一次借用仍然在范围内,即使它没有用于match的情况。这有点不方便:一个聪明的检查员当然可以说借用是不重叠的。我见过有人在线建议使用早期返回以避免问题,如下所示:

match pivots.iter_mut().find(|ref p| key <= p.min_key) {
    Some(ref mut pivot) => {
        pivot.min_key = key;
        pivot.child.insert(key, value);
        return
    },
    None => ()
};
pivots.push(Pivot /* ... */)

但这似乎很难理解,特别是当它意味着将这些代码分解为自己的函数以允许return。是否有更惯用的方式来执行更新或插入操作?

rust borrow-checker
2个回答
6
投票

有一个合并的RFC "non-lexical lifetimes"从长远来看解决了这个问题。使用Rust 2018中的非词法生命周期(Rust 1.31中提供),您的代码按原样运行:

Playground

use std::collections::HashMap;

pub struct Pivot {
    pub min_key: u64,
    pub child: HashMap<u64, ()>,
}

fn update_or_append(pivots: &mut Vec<Pivot>, key: u64, value: ()) {
    match pivots.iter_mut().find(|ref p| key <= p.min_key) {
        Some(pivot) => {
            // If there is one, insert into it and update the pivot key
            pivot.min_key = key;
            pivot.child.insert(key, value);
            return;
        }
        // o/w insert a new leaf at the end
        None => {
            let mut m = HashMap::new();
            m.insert(key, value);
            pivots.push(Pivot {
                min_key: key,
                child: m,
            });
        }
    }
}

fn main() {
    let mut pivots = Vec::new();
    update_or_append(&mut pivots, 100, ());
}

如果这对您的代码不起作用,请查看


在Rust 2018之前,您可以通过一些额外的控制流处理来解决它。

无论更新是否发生,您都可以让您的匹配生成bool值,并使用该值追加下面的条件块。我考虑将“更新或追加”逻辑放入一个单独的函数(更新后使用return)更惯用的方法:

Playground

use std::collections::HashMap;

pub struct Pivot {
    pub min_key: u64,
    pub child: HashMap<u64, ()>,
}

fn update_or_append(pivots: &mut Vec<Pivot>, key: u64, value: ()) {
    if let Some(pivot) = pivots.iter_mut().find(|ref p| key <= p.min_key) {
        // If there is one, insert into it and update the pivot key
        pivot.min_key = key;
        pivot.child.insert(key, value);
        return;
    }
    // otherwise insert a new leaf at the end
    let mut m = HashMap::new();
    m.insert(key, value);
    pivots.push(Pivot {
        min_key: key,
        child: m,
    });
}

fn main() {
    let mut pivots = Vec::new();
    update_or_append(&mut pivots, 100, ());
}

使用bool来跟踪更新是否发生:

Playground

use std::collections::HashMap;

pub struct Pivot {
    pub min_key: u64,
    pub child: HashMap<u64, ()>,
}

fn update_or_append(pivots: &mut Vec<Pivot>, key: u64, value: ()) {
    let updated = match pivots.iter_mut().find(|ref p| key <= p.min_key) {
        Some(pivot) => {
            // If there is one, insert into it and update the pivot key
            pivot.min_key = key;
            pivot.child.insert(key, value);
            true
        }
        // o/w insert a new leaf at the end below
        None => false,
    };
    if !updated {
        let mut m = HashMap::new();
        m.insert(key, value);
        pivots.push(Pivot {
            min_key: key,
            child: m,
        });
    }
}

fn main() {
    let mut pivots = Vec::new();
    update_or_append(&mut pivots, 100, ());
}

3
投票

看起来最好的方法是使用索引而不是迭代器。

match pivots.iter().position(|ref p| key <= p.min_key) {
    Some(i) => {
        // If there is one, insert into it and update the pivot key
        let pivot = &mut pivots[i];
        pivot.min_key = key;
        pivot.child.insert(key, value)
    },
    // o/w, insert a new leaf at the end
    None => pivots.push(Pivot /* ... */)
}

这样,就没有必要使用iter_mut。我对这个替代方案仍然不满意,因为它意味着使用显式索引而不是迭代器。这适用于Vec,但不适用于具有不具有O(1)随机访问索引的结构的容器。

我会接受一个不同的答案,让我避免使用索引。

© www.soinside.com 2019 - 2024. All rights reserved.