Rust, Software Development

Vec With Specific Trait Type

This post is about creating and using a Vec instance with a specific trait type.

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

These trait functions are 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 know 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? We get this:

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

We tested the codes using Rust 1.39.0.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like