Search code examples
rustownership

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


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.