by fluffything · 5y ago · 0 comments
vector<int> v{1,2,3,4}; for (auto&& i: v) v.push_back(i);
Again, in the spirit of becoming more educated, what's the equivalent Rust code? I have `rustc`/`rustup` on my box so I can run that too.
It gives you a small example of what the error is, explains it, and tells you how to fix it.
This is a very nice feature for new people (like myself).
In C++ you (usually) do this with `const`, which is fairly low friction, very statically analyzable, and I'm a little unclear what bug hardcore borrow-checker static stops me or my colleagues from making that `const` can't catch?
#include <vector>
int main()
{
std::vector<int> foo{1,2,3,4,5};
foo.reserve(foo.size()* 2);
for(auto it = foo.begin(), end = foo.end(); it < end; ++it)
foo.push_back(*it);
}- Repeating the vector using the built-in method `Vec::repeat`. This allocates a new vector, but `reserve` is likely to do the same, just implicitly.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
- Using a traditional for loop. There are no lifetime issues, because a new reference is acquired on each iteration. The reserve is not required, but I included it to match your C++ version. https://play.rust-lang.org/?version=stable&mode=debug&editio...
- Creating an array of slices and then concatenating them into a new Vec using the concat method on slices: https://play.rust-lang.org/?version=stable&mode=debug&editio...
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let new_size = v.len()*2;
v = v.into_iter().cycle().take(new_size).collect();
println!("{:?}", v);
}
https://play.rust-lang.org/?version=stable&mode=debug&editio... #include <vector>
void do_stuff(int &a, int &b) {
// stuff
}
int main() {
int my_array[2] = {42, 99};
do_stuff(my_array[0], my_array[1]);
}
That is, how do we take two non-aliasing mutable references into the same array/vector/view/span at the same time. (To be clear, none of the following applies to shared/const references. Those are allowed to alias, and this example will just work.) Notably, the direct translation doesn't compile: fn main() {
let mut my_array = [42, 99];
do_stuff(&mut my_array[0], &mut my_array[1]);
}
Here's the error: error[E0499]: cannot borrow `my_array[_]` as mutable more than once at a time
--> src/main.rs:7:32
|
7 | do_stuff(&mut my_array[0], &mut my_array[1]);
| -------- ---------------- ^^^^^^^^^^^^^^^^ second mutable borrow occurs here
| | |
| | first mutable borrow occurs here
| first borrow later used by call
|
= help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
The issue here is partly that the compiler doesn't understand how indexing works. If it understood that my_array[0] and my_array[1] were disjoint objects, it could maybe deduce that this code was legal. But then the same error would come up again if one of the indexes was non-const, so adding compiler smarts here wouldn't help the general case.Getting multiple mutable references into a single container is tricky in Rust, because you (usually) have to statically guarantee that they don't alias, and how to do that depends on what container you're using. The suggestion in the error message is correct here, and `split_at_mut` is one of our options. Using it would look like this:
fn main() {
let mut my_array = [42, 99];
let (first_slice, second_slice) = my_array.split_at_mut(1);
do_stuff(&mut first_slice[0], &mut second_slice[0]);
}
However, other containers like HashMap don't have `split_at_mut`, and taking two mutable references into e.g. a `HashMap<i32, i32>` would require a different approach. Refactoring our code to hold i32 keys instead of references would be the best option in that case, though it might mean paying for extra lookups. If we couldn't do that, we might have to resort to `Rc<RefCell<i32>>` or trickery with iterators. (This comment is too long already, and I'll spare the gory details.)At a high level, Rust's attitude towards multiple-mutable-references situations is leaning in the direction of "don't do that". There are definitely ways to do it (assuming what you're doing is in fact sound, and you're not actually trying to break the aliasing rule), but many of those ways are advanced and/or not-zero-cost, and in extremis it can require unsafe code. Life in Rust is a lot easier when you refactor things to avoid needing to do this, for example with an entity-component-system sort of architecture.
And that doesn't work, because the v.iter() is sugar for Vec::iter(&v), while the v.push(i) is sugar for Vec::push(&mut v, i) . I think it'd use deref coercion on the i, as Vec::iter(&v) gives you `i: &isize`. If this wasn't ints (or other `Copy` types, for that matter), you'd need to use .into_iter() to consume the Vec and get ownership of the entries while iterating, or use `.push(i.clone())` because `Vec<T>::push(&mut self, T)` is the signature, and you can only go automatically from `&T` to `T` for `Copy` types. Actually, it _may_ even need `v.push(*i)`, thinking about it. Try on https://play.rust-lang.org
C++ is actually a pretty gradually-typed language, and I'm in general a fan of gradual typing. I don't mind that some people prefer BDSM-style typing, but IMHO that goes with GC e.g. Haskell a lot better than it does with trying to print something out or copy it or whatever.
https://play.rust-lang.org/?version=stable&mode=debug&editio...
Alternatively, you can loop over indices instead of values, which doesn’t require the loop to maintain a reference to `v` across iterations:
https://play.rust-lang.org/?version=stable&mode=debug&editio...