Rust Trait

Rust provides many default Trait ready to use. There are:

Using generic type parameter with trait bounds could only able to define a homogeneous container which is checked during compile time. The following example shows how it looks like:

pub struct Screen<T: Draw> {
  pub components: Vec<T>,
}

impl<T> Screen<T> where T: Draw {
  ...
}

If a Screen object created, its field components will contain a vector of the type specified by the type parameter T and will be only able to store that particular type. This limited the flexibility of Rust to include different types that have the same trait.

One could use #202206221113 as in Box<dyn Trait> in order to have a container that could include various types that share the same trait. For example:

pub struct Screen {
  pub components: Vec<Box<dyn Draw>>,
}

pub struct Button {
  ...
}

impl Draw for Button {
  ...
}

pub struct SelectBox {
  ...
}

impl Draw for SelectBox {
  ...
}

By such, Screen will be able to hold a vector of struct that have the trait Draw. This means that the vector could hold both Button and SelectBox at the same time while still being able to be compiled. That being said, the checking is moved to runtime which obviously will introduce some overhead.

Links to this page
#rust #oop