NowNotesTwitter

What is Sized trait?

#rust #programming

It seems intuitive what Sized means. When I first encountered it, I assumed that a Sized type parameter is one that has a known size at compile time. The standard library has a similar definition:

Types with a constant size known at compile time.

Some questions follow: Why does this trait exist? Shouldn't all types implement Sized? If not, then how does one allocate memory for types that don't implement Sized?

Most types indeed do implement the Sized trait. The ones that don't are called dynamically sized types (DST). The two main DSTs exposed by Rust are trait objects (dyn MyTrait) and slices ([T],str) (with one more in the works).

On dynamically sized types, The Rust Reference says:

Most types have a fixed size that is known at compile time and implement the trait Sized. A type with a size that is known only at run-time is called a dynamically sized type (DST) or, informally, an unsized type.
And The Rustonomicon says:
On the surface, this is a bit nonsensical: Rust must know the size and alignment of something in order to correctly work with it! In this regard, DSTs are not normal types. Because they lack a statically known size, these types can only exist behind a pointer.

So although DSTs exist, they can't be accessed directly — only through a pointer to them. And to address my concern, it is not so much that all types should implement Sized, rather all variables, function parameters, const items and static items must be Sized.

But then why do DSTs even exist in Rust? While introducing them, Niko Matsakis notes:

If we change the representation of vectors and slices [to use DSTs], we can have composable types and all the efficiency and flexibility of the current system. The price is that we must distinguish “sized” from “unsized” type parameters.

In essence the trait Sized exists because DSTs exist. And DST exist because, uh well, to make things more 'composable' (don't ask me the details, that is above my pay grade).

Anywho, Sized is a trait that most people writing Rust will not be worrying about most of the time since all generic type parameters are sized by default everywhere. An interesting scenario where one might encounter it is while defining default Trait methods.

Sized is a seemingly simple trait but a lot of things lead to it existing in the standard library! Thanks for reading. If you want to know about DSTs, here are some interesting links to follow through: