Why Is str a Primitive Type?

I was just wondering why it's not a regular type like Box, but a primitive type like integers and floats. I haven't found any topics here.

I implemented my own string slice type for a different encoding not long ago and that worked fine for me. What were the reasons for Rust to not define it as, e.g.

#[repr(transparent)]
struct StringSlice([u8]);

?

If it's about language features, that weren't ready yet at the time of the first stable release of Rust, would it be implemented differently, nowadays, if they had the choice?

1 Like

It needs to be a special type in some way for string literals to work, but it could be redefined as a normal Rust type tagged as a lang item in theory.

2 Likes

Besides being special wrt. string literals, it probably also comes from it having always been a primitive type and there not being anybody who decided to change it. Note that there are even examples of other str-like types in std such as CStr, OsStr and Path.

See Make `str` a `struct str([u8])` · Issue #2692 · rust-lang/rfcs · GitHub

(TL;DR: we almost made it one, but there were some issues, and not a ton of advantages, so we didn't.)

3 Likes

Thank you for the reference! It was very helpful.

I've read through the comments there and the linked issues and from what I can tell, str was in kind of an awkward position. No one seemed to be strictly against converting str to a regular type.

However, concerns were raised regarding the stable release being fairly close and some people already depending on Rust (I'd personally discount this as a non-issue, because the whole point of not having a stable release is for backwards-incompatible changes to be fine). More than that, though, it sounded like str itself was already in a solid position and keeping it as a primitive didn't come with any outstanding drawbacks, so they decided to not touch code that's working as-is and instead invest their time into more important issues.

In conclusion, if the developers were to design strings and string slices from scratch, today, chances are decent, we would be having StrBuf (formerly String) and Str (formerly str), instead.

1 Like

Also Box is just as much a primitive as str, although this is mostly a historical accident. See this blog for details. Also String used to be called StrBuf :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.