Suvorov Ivan
Suvorov Ivan

Reputation: 69

Trait convertion into another trait to use in dyn variable

I have variable like let t1: &dyn T1 or let t1: Box<dyn T1> or like this from external library. I want to use this variable as another trait. So, i have code

fn another_function(let t2: Box<dyn T2>);

let t1: Box<dyn T1> = run_external_function();
another_function(t1);

How can I convert a trait in Rust to another trait? For example

trait T1{}
trait T2{}
impl T2 for dyn T1{}

let t1: &dyn T1 = ;
let t2: &dyn T2 = t1;

I tried it in similar code, but it fails with error

expected trait T2, found trait T1

Upvotes: 1

Views: 81

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70970

Converting a dyn T1 to a dyn T2 cannot work. Think about it: dyn T1 contains the data, but the dyn T2 will also have to contain the type, that is, the vtable. When will we store it? Usually, it is stored in the reference, but there is no reference here!

One way to make this work is to impl T2 for &'_ dyn T1 instead of for dyn T1:

impl T2 for &'_ dyn T1 {}

let t1: &dyn T1 = ...;
let t2: &dyn T2 = &t1;

Now the first reference stores the vtable for T1, and the second reference stores the vtable for T2.

Upvotes: 2

Related Questions