Questioning the ergonomics and terminology of str as a DST from a memory-model perspective

Hello everyone,

While analyzing the memory layout and semantics of Rust’s string types down to the hardware and register level, I have been reflecting on the architectural design choices around str and DSTs in general. I would appreciate some insights into the underlying rationale and history.


1. Terminology: “Dynamically Sized Type”

In low-level systems programming, the word “dynamic” typically denotes runtime type resolution, dynamic dispatch, or late binding. Labeling str as a Dynamically Sized Type (DST) often introduces cognitive friction.

At its core, isn’t str simply an Unsized Type at compile time? Is there a historical or formal type-theoretic rationale why the terminology “Dynamically Sized” was favored over strictly referring to them as “Unsized Types”?


2. Architectural Reality of Naked str

From an assembly and machine architecture point of view, an unsized str cannot exist on the stack as a materialized value. It cannot be bound directly (let x: str), passed by value, or manipulated without an indirection/fat pointer:

  • &str (16-byte fat pointer on 64-bit architectures: pointer + length)
  • Box<str> or Rc<str>

I understand the orthogonal symmetry here: treating str, [T], and dyn Trait uniformly under a single DST framework. However, since a naked str cannot have an independent hardware existence without a fat pointer wrapper, does exposing it as a distinct first-class type at the language level introduce more ergonomic overhead than architectural necessity?


3. Ergonomic Surface Area vs. Orthogonality

In practical codebases, this orthogonal design produces a broad spectrum of string representations:

str, &str, String, &String, Box<str>, Cow<str>, along with trait bounds like AsRef<str> vs Borrow<str>.

While the mathematical symmetry of unifying slices and trait objects under one DST mechanism is conceptually elegant, it comes with non-trivial ergonomic surface area.


Questions for the Community:

  1. Beyond sharing methods across smart pointers (&str, Box<str>, Arc<str>) via Deref, what were the primary design considerations during the early DST RFCs that favored keeping str as a distinct unsized type rather than an intrinsically bundled fat-pointer slice handle?
  2. Are there compiler-internal code generation or layout optimization benefits that strictly depend on this separation?

Looking forward to reading your insights and historical context. Thank you!


I am not deeply familiar with the history here, but I believe that the “unsized” terminology, while still used, is vaguely deprecated because it prompts the misunderstanding that the values of the type have no known size, as opposed to having a run-time known size.

This will be an especially important distinction when extern types, which truly have no known size at all, are stabilized.

This is not true. A str can exist at an address in memory. That’s all that’s needed to qualify something as being a meaningful Rust type. The fact that it can’t ever be the type of a let bound variable is incidental.

The primary purpose of Rust types is to make claims about what interpretations of the contents of memory are valid.

Yes, and that is a feature, not a bug. If you come up with a new kind of container/pointer that supports DSTs, it can work with all kinds of DSTs. If you come up with a custom DST that contains a str, it works with the std containers. If you write code that generically manipulates Arc<T>s, it can work with Arc<str>s.

No.


Note that str could, and arguably should, be defined not as a primitive but as a DST newtype struct in the standard library:

struct str([u8]);

I believe this has been tried, but rejected because it would make compilation slower without much benefit.

I don't know the full history and rationale of the design decision, I just want to make some points.

"dynamic" simply means "the opposite of static". so "dynamically typed" means runtime type checking, "dynamically sized" means runtime boundary checking. late binding is just one example of dynamic typing, but it's not all.

I disagree with the congnitive friction claim. DST is just a concept/term you need to learn as you learn a new language. it's part of the learning process, and it's not a big one really.

yes.

in fact, the definition of a DST is a type that doesn't implement Sized. both terms are used extensively.

that's an implementation detail in current version of the language, and it's not necessarily an inherent limitation of the language semantic (I mean, future language may be extended to support some form of by-value DST).

for example, I remember there have been experiments with unboxed (stack allocated) trait objects as an optimization. e.g. rfc1909 (in progress) and rfc2884 (not accepted). granted, it is not always applicable for all situations, and you still need to access it through some metadata (vtable or length) at runtime, but the data is allocated in the stack frame, so you don't always need the data pointer of a fat pointer.

I don't know what you mean by "fat pointer slice handle", but it's worth pointing out that the reference types like &str in rust is NOT a single type, rather it's a generic type (with a lifetime parameter), so whatever the "handle" you propose, it needs to be generic too, so that you can write signatures like:

// hypothetical `StrHandle`
fn as_str<'a>(&'a self) -> StrHandle<'a>;

does that look any better than &'a str? I don't think so. is it easier to teach to beginners? I don't think so either.

strs can exist on the stack.

fn main() {
    let bytes: [u8; 5] = *b"hello";
    let ref_to_str_on_stack = str::from_utf8(&bytes).unwrap();
    println!("{ref_to_str_on_stack}");
}

I hope you realize this gave me an eyetwitch due to this strictly true, but even more strictly, not true example of "a str on the stack" (in the most strict reading, you have only transmuted a &[u8] to a &str, there is no "true" str on the stack)

It does point out pretty clearly that the only reason for that, though, is the lack of a "sized str" like [T; N] is for [T]. The lack of symmetry is mildly annoying...

Not really. In Rust, a str represents a unsized sequence of UTF-8 bytes. Every now and then, one gets the impression in Rust that all data types which can only be accessed via a specific pointer are managed via the heap. In fact, using str directly is rather difficult. Most of the tie, you'll use something like &' str or static' str. All primitive data types, including str and &, can also be processed via the stack in Rust. This means that although &' str is, at first glance, essentially a pointer to a string, it can still be placed on the stack even if you don’t actually know how long it is. Therefore, we don't need a sized str. It wouldn't be beneficial, because even the unsized str is already enough memory optimized.

So there can't be any other types on the stack, because, well, they are all only transmuted byte slices?

Types only exist in the compiler - so when trying to be needlessly pedantic about whether a str (and not a &str) was "actually" on the stack you can only really mean did the compiler create an object of type str with stack lifetime. My reply was saying that since from_utf8 literally constructs the &str with transmute (or an equivalent) then arguably there is no "real" str in that example at all!

This is, of course, needless pedantry, you get a &'local str which is what you're actually wanting anyway, and if you pull even further into the pedantry rustc would still be representing &str with a structure containing the str type and associating that with a local lifetime in it's checks...

Note that Rust doesn't have typed memory, so there's not really ever any strict anything on the stack. Memory is just memory to Rust (unlike C++).

Types only come into it when you operate on it, so that &str is just as truly on the stack as anything ever is.

Well, C tries to play with that and VLA are even more annoying, in practice, because rules are so crazy when they are involved. Including, but not limiting, to the fact that function that is supposed to accept any type doesn't accept them.

Sure, this is also valid as a view, it's why those transmutes are valid afterall. But I'm not sure I'm philosophically comfortable with either of the claims that a simple transmute of a reference causes the type of the referent to change or that it creates a new object with the new type, that overlaps the original object. I really do need that transmute to be it's own thing - creating a new view of the object you can deref to get a str place, but never a str object.

But we've already spent a bit too long on this ultimately rather silly point, I think!

I was thinking something simpler like str<N> (or whatever) being the statically sized version of str you could create on the stack. What you're talking about might be the other way to "fix" this (a dubious term for a thing that causes no actual problems) - being able to get rid of [T; N] and use bare [T] everywhere so there's no asymmetry. To be clear, I think both of these are technically bad, even if only for not pulling it's weight for str<N>. A language designed purely for looking pretty isn't likely to be much good at doing work :face_savoring_food:

I think it'd be worth trying to define what "object" means to you there.

Especially in the context of dynamic memory. If I

let ptr = alloc::alloc_zeroed(Layout::from_size_align(4, 4).unwrap());

what object did I just make?

If I then do

let a = unsafe { &*ptr.cast::<u32>() };
let b = unsafe { &*ptr.cast::<f32>() };
dbg!(a, b);

did that change anything about the object?

Why would it being "stack" memory instead of "heap" memory change anything?

Not to mention: if the transmute-esqueness means it's not a "real str", neither are any str you read from a file or network or other i/o, any paths/environment/program arguments from the OS, etc. etc.[1] This could be somewhat "fixed" if there was a intrinsic operation to coerce some things to str like there is for [_] and dyn Trait... but in actuality, the type system doesn't care how you got there.

(FWIW, I made my comment because the OP seemed to be drawing a distinction between str and [_]/dyn Trait when saying that str cannot exist on the stack.[2] And I've seen others not realize what I demonstrated was possible, too. Maybe I should point out NumBuffer instead, now that it's stable.)


  1. Or anything in a String, last I checked :upside_down_face: ↩︎

  2. "as a materialized value", whatever that means, it's possible I misinterpreted their point ↩︎

General terminology around "objects" for compilers gets pretty hand wavy around allocator calls, yeah, but in principle they are at least "created" by initializing the pointed-at memory with the value of type T.

Unless I'm missing something, the reborrow example is equivalent to reference transmutes - is that what you're asking?

I guess the question is if there's a distinction, even if not a practical one, between "a real str" and "really creating a str" - I guess I'm happy enough philosophically with the only way to directly "create a str object" is with the str literal syntax, but "any &str still points at a real str place".

Of course there's nothing particularly special about str here, AFAIK all DSTs are only accessable through some reinterpretation of a sized value outside "" / b""

Yeah, I agree otherwise it's neat to point out str can be "on the stack" in the practical sense of having a local lifetime. It's not clear to me if the OP is treating str specially or just as an example, but either way the logic of the counter-example applies to other DSTs perfectly fine.

There is no such distinction because memory doesn't store typed values, it only stores untyped bits. This is different from C++, in C++ memory stores typed objects.

Writing a value v of type T stores the encoding of v in memory. If you later read that memory through type U and it decodes to a value u of type U, then you can say the memory contains u just as much as it contains v.

The same applies to local variables. You can write to a u32 local through a pointer of a different type, and the variable will then contain a different value of type u32 when you read it:

let mut a: u32 = 1;
unsafe { (&mut a as *mut u32 as *mut f32).write(2.0) };
assert_eq!(a, 0x40000000);

The same is true for [u8; 5] and str. If you write some memory with the value *b"hello", and read that memory through &str, then you can say that memory also stores the str value *"hello" just as much as it stores *b"hello".