intorust / intorust.com

Learn Rust real good.
Other
304 stars 25 forks source link

Point out why string values aren't moved into println! #15

Open Gozala opened 7 years ago

Gozala commented 7 years ago

As I was going through the ownership tutorial and then an associated exercise, I wound up with a following solution:

fn print_out(name: String) {
    let (name, devowelized_name) = remove_vowels(name);
    println!("Removing vowels yields {:?}", devowelized_name);

    // Goal #2: What happens when you uncomment the `println` below?
    // Can you change the code above so that the code below compiles
    // successfully?
    //
    let (name, devowelized_name) = remove_vowels(name);
    println!("Removing vowels from {:?} yields {:?}",
             name, devowelized_name);

    // Extra credit: Can you do it without copying any data?
    // (Using only ownership transfer)
}

and later was surprised to find out that second call to remove_vowels was unnecessary & devowelized_name could have being passed to println! twice. My (not validated) guess is that macros don't take ownership unlike functions, but I think it's worth explaining in the tutorial.