Rust string concat with "&*"

I saw this code in rust references

fn f<F : FnOnce() -> String> (g: F) {
    println!("{}", g());

let mut s = String::from("foo");
let t = String::from("bar");

f(|| {
    s += &*t;

Why is string concatenation "s += &t" using the "&" on t?

Strings are managed strs. Hence they dereference into an str. Only std::ops::AddAssign<&'_ str> is implemented on String, so only &strs can be added to a String. I think that it would work just fine with &t instead of &*t, however I'm currently not in a position to test that.

1 Like

I tested it with "&t" and it ran. I thought that &t will deref coercer it into &str without having to use &*t to get &str.

Auto-deref coercions would've done this then, that's an implicit dereference. Note that if you did += t instead, chances are you'd get an error because there's no references in the type anymore for deref coercions to occur.

Thank you for clarifying. The roundabout way to get to &str confused me.

1 Like

No problem. Sorry I couldn't provide links or better examples, since I'm on mobile.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.