'Difference between `&self.stringVal` and `self.stringVal.as_str()`
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()
}
}
Solution 1:[1]
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).
Some programmers may prefer one for its brevity, while others may prefer the other one for its clarity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
