Special types and traits
Certain types and traits that exist in the standard library are known to the Rust compiler. This chapter documents the special features of these types and traits.
Box<T> has a few special features that Rust doesn't currently allow for user
- The dereference operator for
Box<T>produces a place which can be moved from. This means that the
*operator and the destructor of
Box<T>are built-in to the language.
- Methods can take
Box<Self>as a receiver.
- A trait may be implemented for
Box<T>in the same crate as
T, which the orphan rules prevent for other generic types.
std::cell::UnsafeCell<T> is used for interior mutability. It ensures that
the compiler doesn't perform optimisations that are incorrect for such types.
It also ensures that
static items which have a type with interior
mutability aren't placed in memory marked as read only.
Copy trait changes the semantics of a type implementing it. Values
whose type implements
Copy are copied rather than moved upon assignment.
Copy cannot be implemented for types which implement
Drop, or which have
fields that are not
Copy is implemented by the compiler for
- Numeric types
- Tuples of
- Arrays of
- Shared references
- Raw pointers
- Function pointers and function item types
Clone trait is a supertrait of
Copy, so it also needs compiler
generated implementations. It is implemented by the compiler for the following
Send trait indicates that a value of this type is safe to send from one
thread to another.
First, auto traits are automatically implemented using the following rules:
[T]implement the trait if
- Function item types and function pointers automatically implement the trait.
- Structs, enums, unions and tuples implement the trait if all of their fields do.
- Closures implement the trait if the types of all of their captures do. A
closure that captures a
Tby shared reference and a
Uby value implements any auto traits that both
Auto traits can also have negative implementations, shown as
impl !AutoTrait for T in the standard library documentation, that override the automatic
implementations. For example
*mut T has a negative implementation of
*mut T and
(*mut T,) are not
Send. Finally, auto traits may
be added as a bound to any trait object:
Box<Debug + Send + UnwindSafe> is
a valid type.
Sized trait indicates that the size of this type is known at
compile-time; that is, it's not a dynamically sized type. Type parameters
Sized by default.
Sized is always implemented automatically by the
compiler, not by implementation items.