我有以下代码:
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);
}
。
实现这一目标的最佳选择是什么?