intorust / intorust.com

Learn Rust real good.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Shared Borrow @ 18:15

trosel opened this issue · 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?

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/

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

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