3 ms·
This is what the `AsRef` trait is great for impl AsRef<str> for MyCoolString { fn as_ref(&self) -> &str { ... } } To be to
by duped 2y ago
This is what the `AsRef` trait is great for
impl AsRef<str> for MyCoolString {
fn as_ref(&self) -> &str {
...
}
}
To be totally defensive, other library authors can write their APIs like
fn my_cool_function(s: impl AsRef<str>) {
let s: &str = s.as_ref();
}
and now `s` is treated like any other &str. But even if library authors don't program defensively and use `s: &str` in the argument type, callers can always do this:
my_cool_function(my_cool_string.as_ref());
- dubi_steinkek 2y agoIt's possible but I would prefer to just pass &str at that point, leading to less monomorphizations and a simpler API