wayne
wayne

Reputation: 712

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()
    }

}


Upvotes: 4

Views: 414

Answers (1)

hkBst
hkBst

Reputation: 3360

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 Deref trait into a reference to another type. For example, deref coercion can convert &String to &str because String implements the Deref trait 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 the Deref trait. 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 the deref method 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.

Upvotes: 5

Related Questions