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

passing ownership in rust

i am currently learning about ownership and borrowing in rust and how you can’t execute a function two time with the same variable without the borrowing like in this example where it won’t compile

enum Computer{
    Desktop,
    Laptop,
}

fn print_type_of_computer(num: Computer){
    match num {
        Computer::Desktop => println!("this is a desktop"),
        Computer::Laptop => println!("this is a laptop"),
    }
}

fn main() {
    let myComputer :Computer = Computer::Laptop;
    print_type_of_computer(myComputer);
    print_type_of_computer(myComputer);
}

however when i tried this code it worked just fine even if there is no borrowing

fn get_double(num: i32){
    println!("{:?}", num * 2);
}

fn main() {
    let mynum :i32 = 3;
    get_double(mynum);
    get_double(mynum);
}

i am hoping if someone can explain why the code wasn’t accepted for the first case but it was accepted in the second case

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 :

i32 implements Copy, so in that case, the data is actually copied into the function. That means instead of ownership of the original data passing into get_double, a copy of that data is passed.

Computer does not implement Copy though, so it must be borrowed.

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