0

Rust – Vec with a specific Trait Type

In this post, we want to create a Vec instance that only accepts struct instances that implements a particular trait.

In Java

In Java, we would have something like this:

This outputs:

Interfaces and Classes

For the Java interfaces and classes’ definitions, please read Rust – Function that accepts Struct Instance that implements a specific Trait.

In Rust

Now it’s Rust time!

Note: the Rust codes on this post are a bit different from Rust – Function that accepts Struct Instance that implements a specific Trait.

Traits

Note that we user &self  instead of just self .

Implementations

The codes are modified a bit to use &self .

Usage

There are two (2) Vec instances here. The first one is of type Box<dyn Bounceable>  and the other is Box<dyn Inflatable> .

This outputs

Now, why do we need to use Box<dyn Bounceable>>  and Box<dyn Inflatable> instead of just dyn Bounceable  and dyn Inflatable  or just Bounceable and Inflatable?

Trait Sized

Traits are like Java interfaces but they are not the same. They are generally related to things the are dynamic and happen at run-time. Therefore, the Rust compiler will not be able to determine something that is only available at run-time.

Please see https://doc.rust-lang.org/std/marker/trait.Sized.html.

What happens if we do not use Box? This happens:

Hint: using Box allows us to tap into the heap region of the memory.

Tested using Rust 1.39.0.

Karl San Gabriel

Karl San Gabriel

Professional Software Developer