[英]multiple mutable references to disjoint parts of a slice using split_mut or similar
Rust's split_mut function allows you to split a slice by a predicate. Rust 的split_mut函数允许您通过谓词分割切片。 However, the predicate acts on elements of the slice.
但是,谓词作用于切片的元素。 Example:
例子:
let mut v = [10, 40, 30, 20, 60, 50];
for group in v.split_mut(|num| *num % 3 == 0) {
group[0] = 1;
}
assert_eq!(v, [1, 40, 30, 1, 60, 1]);
Can I split a slice in equal parts like this:我可以像这样将切片分成相等的部分:
let mut v = [1,2,3,4,5,6,7,8,9];
and get并得到
&mut[1,2,3]
and &mut[4,5,6]
and &mut[7,8,9]
&mut[1,2,3]
和&mut[4,5,6]
和&mut[7,8,9]
in usch that all these mutables can exist in the same time without me having compilation problems?在 usch 所有这些可变变量可以同时存在而我没有编译问题? I want to have multiple mutable references to disjoint parts of a slice, but the predicate should be on the index of the slice, not the elements .
我想对切片的不相交部分有多个可变引用,但谓词应该在切片的索引上,而不是在 elements 上。
As suggested by Jmb正如Jmb所建议的
You can use split_at_mut to divide a mutable slice into 2 non overlapping mutable slices.您可以使用split_at_mut将一个可变切片分成 2 个不重叠的可变切片。
fn main() {
let mut v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Needs to be a multiple of v
let number_of_parts = 5;
let mid = v.len() / number_of_parts;
let mut res = Vec::new();
let mut ret = &mut v[..];
for _ in 0..number_of_parts {
let (head, tail) = ret.split_at_mut(mid);
res.push(head);
ret = tail;
}
println!("Parts: {:?}.", res);
}
As Suggested by Õmer Erden根据Õmer Erden 的建议
You can use chunks_mut to iterate over a mutable slice an return non overlapping mutable slices.您可以使用chunks_mut迭代可变切片并返回不重叠的可变切片。
fn main() {
let mut v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Needs to be a multiple of v
let number_of_parts = 5;
let mid = v.len() / number_of_parts;
let mut res = Vec::new();
for chunk in v.chunks_mut(mid) {
res.push(chunk);
}
println!("Parts: {:?}.", res);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.