在Rust中的线程使用的闭包中使用泛型T?

时间:2019-01-30 08:21:32

标签: multithreading generics rust closures ownership

Rust高兴地让我编译了这个简单的函数:

fn spawn1(input: String) {
    ::std::thread::spawn(move || {
        input;
    });
}

但是如果我通过将String更改为通用类型T使它更通用,则会遇到问题:

fn spawn2<T>(input: T)
    where T: Send
{
    ::std::thread::spawn(move || {
        input;
    });
}
error[E0310]: the parameter type `T` may not live long enough
  --> src/lib.rs:10:5
   |
7  | fn spawn2<T>(input: T)
   |           - help: consider adding an explicit lifetime bound `T: 'static`...
...
10 |     ::std::thread::spawn(move || {
   |     ^^^^^^^^^^^^^^^^^^^^
   |
note: ...so that the type `[closure@src/lib.rs:10:26: 12:6 input:T]` will meet its required lifetime bounds
  --> src/lib.rs:10:5
   |
10 |     ::std::thread::spawn(move || {
   |     ^^^^^^^^^^^^^^^^^^^^

我可以通过对spawn2进行一些限制而不是T来使Send工作吗?我需要为T指定什么最小属性才能使其正常工作?

我猜想这与所有权有关。如果闭包可以使T的所有权更强大,那么就不会有终身麻烦。我是否需要以某种方式指定T应该拥有而不是借用?

我知道设置T: 'static可以使其编译,但是限制没有比需要的更多吗?

0 个答案:

没有答案