R
R
RADION NAZMIEV2021-04-21 04:05:39
Rust
RADION NAZMIEV, 2021-04-21 04:05:39

How to fix used of moved value error?

When hovering over row and temp[col] vec[row][col] = temp[col]it gives out Use of moved value which I can't figure out where it's happening. The same with "r" from vec[r].first()
also the compiler gives index out of bounds: the len is 2 but the index is 2

'E' => { (0..rows).for_each(|row| {
                    let temp = (0..cols)
                        .rev()
                        .map(|col| vec[row][col])
                        .filter(|&x| x != 0)
                        .collect();
                    let mut temp = tilt_sequence(temp, cols);
                    temp = temp.into_iter().rev().collect();
                    (0..cols).for_each(|col| vec[row][col] = temp[col]);
                });
                    while (0..rows).map(|r| vec[r].first().unwrap()).all(|&x| x == 0) {
                        (0..rows).for_each(|r| {vec[r].remove(0);});
                    };
                },



Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-04-30
@radionnazmiev

temp = temp.into_iter().rev().collect();
(0..cols).for_each(|col| vec[row][col] = temp[col]);

tempowns some memory
(0..cols).for_eachiterates and calls the cols function passed to it once
the closure devoted to for_each grabs vec by &mut reference and temp by value
on the first iteration temp[0] does move to vec[row][0], since in Rust's memory model neither one type cannot exist in the form of a "stub with a hole", the compiler appends drop(temp) to the end of the function |col| vec[row][col] = temp[col], and since temp is captured by the closure by value (in fact, it is part of the closure), at the end of the iteration of the loop inside for_each it is also itself the closure is dropped.
In other words, for_each wants FnMut from you, and you only gave it FnOnce.
I think one of these functions will help you:
https://doc.rust-lang.org/beta/std/mem/fn.take.html
https://doc.rust-lang.org/beta/std/mem/fn .replace.html
index out of bounds: the len is 2 but the index is 2
This is not a compilation error, but a runtime panic, which says that you have gone beyond the slice boundary
PS I hope you understand what is O(n 3 ) here?
while (0..rows).map(|r| vec[r].first().unwrap()).all(|&x| x == 0) {
    (0..rows).for_each(|r| {vec[r].remove(0);});
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question