我想在将该类型的变量移至线程的函数中使用泛型:
use std::thread;
fn ret_x<T: Send>(x: T) -> T {
let handle = thread::spawn(move || return x);
return handle.join().unwrap();
}
执行此操作时,会出现错误:
error[E0310]: the parameter type `T` may not live long enough
--> src/lib.rs:4:18
|
3 | fn ret_x<T: Send>(x: T) -> T {
| -- help: consider adding an explicit lifetime bound `T: 'static`...
4 | let handle = thread::spawn(move || return x);
| ^^^^^^^^^^^^^
|
note: ...so that the type `[closure@src/lib.rs:4:32: 4:48 x:T]` will meet its required lifetime bounds
--> src/lib.rs:4:18
|
4 | let handle = thread::spawn(move || return x);
| ^^^^^^^^^^^^^
error[E0310]: the parameter type `T` may not live long enough
--> src/lib.rs:4:18
|
3 | fn ret_x<T: Send>(x: T) -> T {
| -- help: consider adding an explicit lifetime bound `T: 'static`...
4 | let handle = thread::spawn(move || return x);
| ^^^^^^^^^^^^^
|
note: ...so that the type `T` will meet its required lifetime bounds
--> src/lib.rs:4:18
|
4 | let handle = thread::spawn(move || return x);
| ^^^^^^^^^^^^^
如果我给T
赋予生命周期限制'static
,则它将编译而不会出错,但是由于该函数需要在函数内部声明的变量上使用,因此不能为'static
。 / p>
T
将被拥有,而不是引用。有什么办法可以指定吗?