Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shared Borrow @ 18:15 #11

Open
trosel opened this issue Oct 5, 2016 · 3 comments
Open

Shared Borrow @ 18:15 #11

trosel opened this issue Oct 5, 2016 · 3 comments

Comments

@trosel
Copy link

trosel commented Oct 5, 2016

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 trosel changed the title Shared Borrow [18:15 Shared Borrow @ 18:15 Oct 5, 2016
@ests
Copy link
Contributor

ests commented Oct 6, 2016

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
Copy link

swuecho commented Nov 25, 2016

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
Copy link

doup commented Sep 19, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants