Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass a value to a function without moving ownership, just by passing the value in Rust?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s quite Simple.

  1. copy variable when pass to function. use {var}.copy()
  2. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading