Let v
be Vec<HashSet<usize>>
.
Is it possible to update v[i]
while iterating v[i - 1]
?
Normally, Rust's ownership rule doesn't allow this, but I believe some way should exist since v[i]
and v[i - 1]
are essentially independent.
unsafe
is allowed because unsafe
sometimes lets us bypass (in a sense) the ownership rule. (For example, swapping values of HashMap
is normally impossible, but using unsafe
makes it possible. ref: swapping two entries of a HashMap)
Please assume v.len()
is very large because, if v.len()
is small, you can give up using Vec
container in the first place.
Very artificial but minimum working example is shown below (Rust Playground). This type of source code is often seen in doing dynamic programming.
use std::collections::HashSet;
fn main() {
let n = 100000;
let mut v = vec![HashSet::new(); n];
v[0].insert(0);
for i in 1..n {
v[i] = v[i - 1].clone(); //This `clone()` is necessarily.
let prev = v[i - 1].clone(); //I want to eliminate this `clone()`.
prev.iter().for_each(|e| {
v[i].insert(*e + 1);
})
}
println!("{:?}", v); //=> [{0}, {0, 1}, {0, 1, 2}, {0, 1, 2, 3}, ...]
}