Could anyone tell me what's the difference between the 2 ways for returning the &str value for name of User? Both compile but I'm not sure if there's a preferred one.
pub struct User {
name: String,
}
impl User {
pub fn name(&self) -> &str {
// way1
&self.name
// way2
// self.name.as_str()
}
}
Using & on a String gives a &String and relies on deref coercion to arrive at the desired &str type, but as_str unambiguously gives a &str (while using deref coercion internally). Without deref coercion one would have to write &s[..] to turn a String s into a &str.
Deref coercion converts a reference to a type that implements the
Dereftrait into a reference to another type. For example, deref coercion can convert&Stringto&strbecauseStringimplements theDereftrait such that it returns&str. Deref coercion is a convenience Rust performs on arguments to functions and methods, and works only on types that implement theDereftrait. It happens automatically when we pass a reference to a particular type’s value as an argument to a function or method that doesn’t match the parameter type in the function or method definition. A sequence of calls to thederefmethod converts the type we provided into the type the parameter needs. -- The Rust Programming Language (Chapter 15)
Some programmers may prefer one for its brevity, while others may prefer the other one for its clarity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With