intorust / intorust.com

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

Shared Borrow @ 18:15 #11

Open trosel opened 7 years ago

trosel commented 7 years ago
pub fn main() {
    let string = format!("my friend");
    greet(&string[3..]);
    greet(&string);
}

fn greet(name: &str) {
    println!("Hello, {}!", &name);
}

The above code is the exact same as the below code (the difference is the final ampersand in greet).

pub fn main() {
    let string = format!("my friend");
    greet(&string[3..]);
    greet(&string);
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}

Can you explain why this is not different? The first code would basically be a... double borrow?

ests commented 7 years ago

Well I am new to Rust, so everything I write may be wrong :)

The difference in code is the type of the name variable on the last line. In the second example it's &strwhile in the first it's &&str. As no matter how many references you create, it will still point to original value. Hence, you can do &&&&&&&name and it will still work. And it will because macros like format! or println! will accept any argument that implements its formatting traits. You can read about those traits here: https://doc.rust-lang.org/std/fmt/

swuecho commented 7 years ago

I thought it was this. https://doc.rust-lang.org/book/deref-coercions.html

for the deref coercions, I wonder how the compiler did this?

Could C compiler do this too? (so you do not have to deref a point?)

doup commented 6 years ago

This is something that also confuses me, and the answer seems to be how macros are handled in Rust: https://stackoverflow.com/questions/30450399/does-println-borrow-or-own-the-variable (yet I still don't understand it)

It confuses me that println! doesn't take ownership of the variables, I've made and example here: https://play.rust-lang.org/?gist=8305c7e76dabdb2faf1a6f3c23b4cfcb&version=stable

I'm new to Rust so I might be interpreting this wrong...