Passing reference to function

Hi,
How is the intended way for passing a reference to a function?
In my opinion, the firs call to bar, resp. println! is the correct one, since it is already a reference. But why are both "variants" possible (since the second call would pass a &&str)? Does the compiler optimizes that?

fn main() {
    let foo: &str = "Foo";
    bar(foo);
    bar(&foo);
}

fn bar(foo: &str) {
    println!("function called: {}", foo);
    println!("function called: {}", &foo);
}

The second case is talking advantage of deref coercion -- the &&str will be dereferenced to &str to make the actual call. This is more useful when the underlying type changes through Deref, like using &String for a &str argument.

Note that println is not a function but a macro, and you can't expect things to work the same with them. For example you can pass a String to println by value, you can still use it afterwards because the macro inserts some sort of borrow for you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.