Comment

Comment by duped

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());
parent duped 2 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton