1

I have the below code:

trait Trt {
    fn perform_magic(&self);
}

struct X {
    t: Box<Trt>,
}

impl X {
    fn new<T: Trt>(t: T) -> X {
        X {
            t: Box::new(t),
        }
    }
}

struct Y;

impl Trt for Y {
    fn perform_magic(&self) {
        println!("Magic!");
    }
}

fn main() {
    let y = Y;
    let x = X::new(y);
}

I want to transfer ownership of the function argument t into the new Box which will be handed over to the t field in X, but this code will not work:

error[E0310]: the parameter type `T` may not live long enough
  --> tst.rs:14:19
   |
14 |                t: Box::new(t),
   |                   ^^^^^^^^^^^
   |
   = help: consider adding an explicit lifetime bound `T: 'static`...
note: ...so that the type `T` will meet its required lifetime bounds
  --> tst.rs:14:19
   |
14 |                t: Box::new(t),
   |                   ^^^^^^^^^^^

I would like to have the object x contain a Box which refers (owns) to y.

What is the best option to achieve this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Windel
  • 499
  • 4
  • 11

0 Answers0