I wrote a max
function which takes a Vec
as a parameter. It works as I expected. Then I added a min
function the same as the max
function:
fn main() {
let my_array = vec![61, 14, 71, 23, 42, 8, 13, 66];
let max = max(my_array);
let min = min(my_array);
println!("Max value is {}.", max);
}
fn max(array: Vec<i32>) -> i32 {
let mut max = array[0];
for val in array {
if max < val {
max = val;
}
}
max
}
fn min(array: Vec<i32>) -> i32 {
let mut min = array[0];
for val in array {
if min > val {
min = val;
}
}
min
}
Rust reports an error if I put the same my_array
parameter on the call to min
:
error[E0382]: use of moved value: `my_array`
--> src/main.rs:4:19
|
2 | let my_array = vec![61, 14, 71, 23, 42, 8, 13, 66];
| -------- move occurs because `my_array` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 | let max = max(my_array);
| -------- value moved here
4 | let min = min(my_array);
| ^^^^^^^^ value used here after move
How can I write code that works?