rust-analyzer / smol_str

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Implement `AsRef<str>`

MonliH opened this issue · comments

It would be nice if the current smol_str implemented AsRef<str>, as many functions rely on that genric bound, and it's slightly tedious to use the as_str method each time. Currently, there's already an .as_str() method, so implementing this would be quite trivial:

impl AsRef<str> for SmolStr {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

I could open a pr if you'd like.

Hmm, it seems like the compiler is not happy with both From<T> and AsRef<str>, for some reason:

error[E0119]: conflicting implementations of trait `std::convert::From<SmolStr>` for type `SmolStr`:
   --> src/lib.rs:282:1
    |
282 | / impl<T> From<T> for SmolStr
283 | | where
284 | |     T: Into<String> + AsRef<str>,
285 | | {
...   |
288 | |     }
289 | | }
    | |_^
    |
    = note: conflicting implementation in crate `core`:
            - impl<T> From<T> for T;

I think it's because the compiler doesn't want to allow the SmolStr::from method to take in a SmolStr, which would make the From::from call ambiguous. Seems like there's no way to fix this for now, so maybe it's not possible to implement both traits. see stackoverflow question