intorust icon indicating copy to clipboard operation
intorust copied to clipboard

Shared Borrow @ 18:15

Open trosel opened this issue 9 years ago • 3 comments

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?

trosel avatar Oct 05 '16 21:10 trosel

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/

ests avatar Oct 06 '16 08:10 ests

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?)

swuecho avatar Nov 25 '16 23:11 swuecho

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...

doup avatar Sep 19 '17 11:09 doup