by codedokode · 2y ago · 0 comments
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());But the thing about String is that it allows you to push data at the end (like Java's StringBuilder). I think there is no commonly used trait for that, no.
Note that not all owned string types can be appended at the end. Box<str> for example is just like String but without a .push_str() method. (This saves some bytes because it doesn't need a spare capacity)
If your string is not UTF-8 then usually you convert it at API boundaries, to deal with UTF-8 stuff internally (or at least WTF-8)