Hacker News new | past | comments | ask | show | jobs | submit login

I wonder, is there a "string-like interface" in Rust or one has to rewrite all the code when changing string implementation? Also if you want to change implementation in half of the code, is there automatic convertion between implementations?



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


It's possible but I would prefer to just pass &str at that point, leading to less monomorphizations and a simpler API


For read-only strings you pass around &str usually if you can borrow at all, and all UTF-8 string types should be compatible with it. AsRef is just a trait for "all types that can be converted into &str as needed" so if you use AsRef you need to have immutable strings too

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)




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: