This is just example code.
fn main() {
let mut vec = vec![4, 3, 6, 7, 5, 8, 1, 2, 9, 0, 1];
println!("{:?}", solution(&mut vec));
}
fn solution(vec: &mut std::vec::Vec<i32>) -> (i32, i32, i32) {
let mut copy = vec;
copy.sort();
println!("{:?}",copy);
let mut len: i32 = match copy.len().try_into() {
Ok(v) => v,
Err(_) => panic!("Error!"),
};
let avg = (copy.last().unwrap() + copy.first().unwrap()) / 2;
let median = copy[copy.len() / 2];
let mode = {
let mut hmap = HashMap::new();
for element in copy {
let count = hmap.entry(element).or_insert(0);
*count += 1;
}
let mut max = 0;
for i in hmap.keys() {
if hmap[i] > max {
max = **i;
}
}
max
};
(avg, median, mode)
}
In this code, I copied vec variable in solution function to caculate something because of Ownership rules. But In this case, solution function need just a value of vec variable. As a result, the vec variable’s values can change. I want to transfer ownership or just pass a value when passing it to a function.
>Solution :
It’s quite Simple.
- copy variable when pass to function. use {var}.copy()
- If you want modify value, just assign a return to variable
fn main() {
let mut vec
...
vec2 = foo(vec.copy());
...
}
fn foo(vec: std::vec::Vec<T>) -> V {
...
return something
}
In this case, You finally no transfer ownership, pass only values to function.