0

Vec With Specific Trait Type

Last Updated on

This post is about creating and using a Vec instance with a specific trait type. The insta that only accepts struct instances that implements a particular trait.

In Java

We would have something like this in Java.

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 that the Rust codes on this post are a bit different from Rust – Function that accepts Struct Instance that implements a specific Trait.

Traits

We are using &self  instead of just self.

Trait Type Implementations

This too is using &self.

Vec with a specific Trait Type

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

A compiler does not anything about run-time. There’s no way for it to know how a trait behaves 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