How marker traits works

i don't understand how a marker trait works. These are basically empty that means they don't have any functions associated with it then how does traits like these enforce certain properties on types which implement these. For example lets say i have type T which implements sized which means
that type T size is known at compile time. Since sized has zero method in it, how does rust compiler confirms type T size is known at compile time. Similarly how does rust compiler confirms a type which implementing Send is thread safe.

Great answer here on URLO I think you might find useful:


You seem to be confusing the implementation of a trait with requiring types to conform to such a trait bound.

Magic traits like Sized are implemented by the compiler upon inspecting the structure of a type. (If a type recursively contains unsized types, it's unsized, otherwise it's sized.)

This is completely unrelated to whether or not they have any methods. The Sized trait could as well have an associated method size_of() returning the size; this would not affect how and for what types it is implemented in any way.

How marker traits are used is another question. That's in fact why they are called markers: they don't enable additional methods to be called on a bounded type, they merely mark that type as a member of a particular set, having a particular property.

For example, accepting a type bounded by Send + Sync means that your code can safely access it from another thread (whether it be by value or by reference). This is an important soundness property required for making sure that low-level threaded code remains memory-safe. There is no need for methods on these traits, because implementing types are known to have the thread-safety property merely by implementing the traits, even if empty.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.