If you want to loop a one-dimensional array into a triangle and process all the combinations, I think Java will be as follows.
Foo[]data=...;
for(inti=0;i<data.length();i++){
for(int j=i+1;j<data.length();j++){
// Calculated using various data[i] and data[j]
data[i].bar+=...;
data[j].bar+=...;
}
}
Is there a way to do this with Rust and Iterator only?
I thought it would be better if I could make a copy so that I wouldn't change the original iter
in the internal loop (see the original data instead of copying), but I couldn't find such a function.
let mut data:Vec<Foo>=...;
let mutter=data.iter_mut();
whilelet Some(idata)=iter.next(){
// I want to avoid consuming `iter` for external loops in internal loops
let mut inner_iter=iter.clone();
for jdata in inner_iter{
// Calculated using various idata and jdata
idata.bar+=...;
jdata.bar+=...;
}
}
If the emulated iterator std::slice::Iter
, it is possible, but it does not implement the mutable iterator std:::IterMode
.This is a deliberate constraint to achieve the safety of the Rust language.
The Rust language does not permit the presence of multiple mutable references pointing to the same object.From the point of view of having the ability to rewrite a target object, a mutable iterator has the equivalent of a mutable reference, so you cannot duplicate a mutable iterator.
Either implement it on an index value basis, or use Interior Mutability via RefCell
.The latter is equivalent to delaying the compilation ownership inspection to the execution inspection.
let muta:Vec<i32>=(0..10).collect();
for in 1..a.len() {
let(af,ae) = a.split_at_mut(i);
for vinae.iter_mut(){
af[i-1]+=*v;
*v+=1
}
}
You can use split_at_mut
to view one mutable array in two mutable arrays.I'm using index for the first for, so I can't say it's just the iterator, but w
© 2024 OneMinuteCode. All rights reserved.