Warning
This post was published 38 days ago. The information described in this article may have changed.
It's best if you don't access bc for that you'd need to do the exercises, which will skew the statistics, but it's from last part of Ch 8 Ownership Inventory #2 - The Rust Programming Language
they give this fn
:
fn remove_zeros(v: &mut Vec<i32>) {
for (i, t) in v.iter().enumerate().rev() {
if *t == 0 {
v.remove(i);
v.shrink_to_fit();
}
}
}
the question is, assuming .iter()
is allowed to borrow (bypass the safety of re-borrowing an already &mut
vector), whether the calls below produce would undefined behaviour (both do in the solution):
let mut v = vec![1, 2, 0, 3];
remove_zeros(&mut v);
let mut v = vec![5, 5, 0];
remove_zeros(&mut v);
println!("{:?}", v);
I assumed that:
iter()
works by calling next()
on every iteration until i
is longer than the vector's length (so shrink/grow it isn't a problem, assuming the length its updated)So in my opinion in the first case the result is what one would expect that is 1,2,3 and in the second case it is also 5,5.
I'm unsure what I misunderstood.
It'd be useful if an answer it compatible or at the level of the corresponding section https://rust-book.cs.brown.edu/ch08-01-vectors.html#safely-using-iterators, and not too advanced
8 posts - 4 participants
🏷️ rust_feed