cle*_*ggy 1 reference vector rust borrow-checker borrowing
我有一个大型嵌套数据结构,想取出一些部分来进行处理。最终,我想将部分发送到多个线程进行更新,但我想先了解一下我下面说明的简单示例。在 CI 中只会组装一个相关指针的数组。这在 Rust 中似乎是可行的,因为内部向量永远不需要多个可变引用。这是示例代码。
fn main() {
let mut data = Data::new(vec![2, 3, 4]);
// this works
let slice = data.get_mut_slice(1);
slice[2] = 5.0;
println!("{:?}", data);
// what I would like to do
// let slices = data.get_mut_slices(vec![0, 1]);
// slices[0][0] = 2.0;
// slices[1][0] = 3.0;
// println!("{:?}", data);
}
#[derive(Debug)]
struct Data {
data: Vec<Vec<f64>>,
}
impl Data {
fn new(lengths: Vec<usize>) -> Data {
Data {
data: lengths.iter().map(|n| vec![0_f64; *n]).collect(),
}
}
fn get_mut_slice(&mut self, index: usize) -> &mut [f64] {
&mut self.data[index][..]
}
// doesnt work
// fn get_mut_slices(&mut self, indexes: Vec<usize>) -> Vec<&mut [f64]> {
// indexes.iter().map(|i| self.get_mut_slice(*i)).collect()
// }
}
Run Code Online (Sandbox Code Playgroud)
只要您非常小心,使用安全的 Rust 就可以做到这一点。诀窍是利用标准库中安全.iter_mut()和.nth()方法背后的不安全 Rust 代码Vec。这是一个工作示例,其中包含解释上下文中的代码的注释:
fn main() {
let mut data = Data::new(vec![2, 3, 4]);
// this works
let slice = data.get_mut_slice(1);
slice[2] = 5.0;
println!("{:?}", data);
// and now this works too!
let mut slices = data.get_mut_slices(vec![0, 1]);
slices[0][0] = 2.0;
slices[1][0] = 3.0;
println!("{:?}", data);
}
#[derive(Debug)]
struct Data {
data: Vec<Vec<f64>>,
}
impl Data {
fn new(lengths: Vec<usize>) -> Data {
Data {
data: lengths.iter().map(|n| vec![0_f64; *n]).collect(),
}
}
fn get_mut_slice(&mut self, index: usize) -> &mut [f64] {
&mut self.data[index][..]
}
// now works!
fn get_mut_slices(&mut self, mut indexes: Vec<usize>) -> Vec<&mut [f64]> {
// sort indexes for easier processing
indexes.sort();
let index_len = indexes.len();
// early return for edge case
if index_len == 0 {
return Vec::new();
}
// check that the largest index is in bounds
let max_index = indexes[index_len - 1];
if max_index > self.data.len() {
panic!("{} index is out of bounds of data", max_index);
}
// check that we have no overlapping indexes
indexes.dedup();
let uniq_index_len = indexes.len();
if index_len != uniq_index_len {
panic!("cannot return aliased mut refs to overlapping indexes");
}
// leverage the unsafe code that's written in the standard library
// to safely get multiple unique disjoint mutable references
// out of the Vec
let mut mut_slices_iter = self.data.iter_mut();
let mut mut_slices = Vec::with_capacity(index_len);
let mut last_index = 0;
for curr_index in indexes {
mut_slices.push(
mut_slices_iter
.nth(curr_index - last_index)
.unwrap()
.as_mut_slice(),
);
last_index = curr_index;
}
// return results
mut_slices
}
}
Run Code Online (Sandbox Code Playgroud)
我相信我了解到的是,Rust 编译器在这种情况下需要一个迭代器,因为这是它知道每个 mut 切片来自不同向量的唯一方法。
编译器实际上并不知道这一点。它只知道迭代器返回 mut 引用。底层实现使用不安全的 Rust,但方法iter_mut()本身是安全的,因为该实现保证每个 mut ref 仅发出一次,并且所有 mut ref 都是唯一的。
mut_slices_iter如果在 for 循环中创建了另一个(可以两次获取相同的数据),编译器会抱怨吗?
是的。调用可变iter_mut()借用Vec它并且相同数据的重叠可变借用违反了 Rust 的所有权规则,因此您不能iter_mut()在同一范围内调用两次(除非第一次调用返回的迭代器在第二次调用之前被删除)。
另外,我是否正确,该
.nth方法将调用next()n 次,因此最终在第一个轴上是 theta(n) ?
不完全的。这是默认的实现,但是通过调用nth返回的迭代器使用它自己的自定义实现,并且它似乎跳过迭代器中过去的项目而不调用,所以它应该像您定期索引到 一样快,即获得 3 个随机索引items using在 10000 个项目的迭代器上与在 10 个项目的迭代器上一样快,尽管这仅适用于从支持快速随机访问(如s)的集合创建的迭代器。iter_mut()Vecnext()Vec.nth()Vec
| 归档时间: |
|
| 查看次数: |
5038 次 |
| 最近记录: |