Assume we already know that String
can become &str
after deref for
impl ops::Deref for String {
type Target = str;
#[inline]
fn deref(&self) -> &str {
unsafe { str::from_utf8_unchecked(&self.vec) }
}
}
This code can work because there is a deref chain:
&String --> String ---> &str
.fn uppercase(s: &str) -> String { s.to_uppercase() } fn main() { let s = String::from("hello"); assert_eq!(uppercase(&s), "HELLO"); }
Why does the code below not work even though there is a deref chain
String ---> &str
?fn uppercase(s: &str) -> String { s.to_uppercase() } fn main() { let s = String::from("hello"); assert_eq!(uppercase(s), "HELLO"); }
Why does the code below not work even though there is a deref chain:
&String --> String
?fn uppercase(s: String) -> String { s.to_uppercase() } fn main() { let s = String::from("hello"); assert_eq!(uppercase(&s), "HELLO"); }