My question is in the comment towards the bottom of the function. When I added the "if" at the bottom I then needed to update the way I was iterating sorted_nums
by adding .iter().cloned()
. I have it working, but I don't understand why I had to do this. Could someone please explain it to me? Any other criticisms (advice) are welcome. I'm a seasoned Python developer taking my first steps into Rust.
pub fn missing_number(nums: Vec<i32>) -> i32 {
// https://leetcode.com/problems/missing-number/
let mut prev_num: Option<i32> = None;
let mut sorted_nums = nums.clone();
sorted_nums.sort();
for num in sorted_nums.iter().cloned() {
if prev_num.is_some() {
let expected = prev_num.unwrap() + 1;
if num != expected {
return expected;
}
} else if prev_num.is_none() && num != 0 {
return 0;
}
prev_num = Some(num);
}
// After adding this "if" I had to add `.iter().cloned()`
// to the loop and I don't really know why.
if sorted_nums[sorted_nums.len() - 1] != sorted_nums.len() as i32 {
return sorted_nums[sorted_nums.len() - 1] + 1;
}
panic!("hhhh");
}
Without .iter().cloned()
I get these errors
let mut sorted_nums = nums.clone();
// Diagnostics:
// 1. move occurs because `sorted_nums` has type `Vec<i32>`, which does not implement the `Copy` trait [E0382]
for num in sorted_nums {
// Diagnostics:
// 1. `sorted_nums` moved due to this implicit call to `.into_iter()` [E0382]
// 2. consider iterating over a slice of the `Vec<i32>`'s content to avoid moving into the `for` loop: `&` [E0382]
Instead of doing the slice, I seemed to have done a clone?
if sorted_nums[sorted_nums.len() - 1] != sorted_nums.len() as i32 {
// Diagnostics:
// 1. borrow of moved value: `sorted_nums`
// value borrowed here after move [E0382]
I essentially don't understand any of these errors. Help understanding would be appreciated. Thanks!