如何移动函数参数的所有权?

时间:2017-11-22 20:21:35

标签: rust ownership

我有以下代码:

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);
}

我想将函数参数t的所有权转移到新的Box中,该t将移交给X中的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), | ^^^^^^^^^^^ 字段,但此代码不会工作:

x

我希望对象Box包含一个y,它引用(拥有)using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService<MyProjectContext>(); // pass context to relevant Classes/Functions, i.e. MyClass myClass = new MyClass(); myClass.ImportOperatorList(context); }

实现这一目标的最佳选择是什么?

0 个答案:

没有答案