In this section, we'll look at some of the advanced types in Rust. Let's first start with unsized types.
Unsized types are categories of types that are first encountered if one tries to create a variable of the type, str
. We know that we can create and use string references only behind references such as &str
. Let's see what error message we get if we try to create a str
type:
// unsized_types.rs fn main() { let a: str = "2048"; }
We get the following error upon compilation:
By default, Rust creates a reference type of str
as 'static str
. The error message mentions that all local variables—values that live on the stack—must have a statically known size at compile time. This is because the stack memory is finite and we cannot have infinite- or dynamic-sized types. Similarly, there are other instances of types that are unsized:
[T]
: This is a slice of type,T
. They can only be used as&[T]
or&mut [T]
.dyn Trait
: This is a trait object. They can only...