In this example code from the Rust documentation :
fn takes_str(s: &str) { }
let s = String::from("Hello");
takes_str(&s);
What exactly is going on behind the scenes that causes &s
to become a &str
instead of a &String
? The documentation seems to suggest that there's some dereferencing going on, but I thought *
was for dereferencing, not &
?
What's going on here is called deref coercions . These allow references to types that implement the Deref trait to be used in place of references to other types. As your example shows, &String
can be used anywhere a &str
is required, because String
implements Deref
to str
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.