Let's say that you had a Rust trait that you want to turn into a trait object. To do that, you need to make sure that the trait is "object safe", (i.e., can be expressed as a data pointer and a pointer to a vtable of concretely typed functions). Here is an example of such a trait, expressing an evaluation node in a hypothetical array-based programming language:

trait Expression { fn eval (& self ) -> Vec < i32 >; }

Now that we have an object-safe trait, we can create trait objects for it by wrapping implementer structs in a pointer type:

struct Num ( i32 ); impl Expression for Num { fn eval (& self ) -> Vec < i32 > { Vec ::new( self .0) } } fn main () { let expr = Box ::new( Num (5)) as Box < dyn Expression >; assert_eq! (expr.eval(), vec! [ 5 ]); }

This works out nicely for the Num struct because its inner type, i32 , implements Copy . Copying an i32 is very efficient.

However, what if we had a struct that was much larger in size?

/// This operator produces a vector of its inputs doubled. struct Double ( Vec < i32 >);

The only way that this operator is going to work is by creating a new Vec to push the doubled elements into:

impl Expression for Double { fn eval (& self ) -> Vec < i32 > { self .0.iter().map(|v| v * 2).collect() // New Vec allocated here: ^^^^^^^^^ } }

And this is basically fine. For most instances, this is going to be okay because you want the trait objects to live for as long as possible. Using this method, an evaluation node can be eval'd as many times as we want:

fn main () { let expr = Box ::new( Double ( vec! [ 1, 2, 3, 4, 5 ])) as Box < dyn Expression >; assert_eq! (expr.eval(), vec! [ 2, 4, 6, 8, 10 ]); assert_eq! (expr.eval(), vec! [ 2, 4, 6, 8, 10 ]); assert_eq! (expr.eval(), vec! [ 2, 4, 6, 8, 10 ]); assert_eq! (expr.eval(), vec! [ 2, 4, 6, 8, 10 ]); // etc... }

This is a pattern you'd typically see with interpreters; code is often stored as functions that are run multiple times.

However, if we only intend to evaluate this once, there is a better solution.