【问题标题】:Rustlang sending generic data with channel? Which traits/ markers have to be implemented to do that?Rustlang 使用通道发送通用数据?必须实现哪些特征/标记才能做到这一点?
【发布时间】:2019-09-05 19:56:23
【问题描述】:

必须在泛型类型 T 上实现哪些特征和标记才能通过通道发送? Type T 不应包含任何引用,并拥有来自任何引用的“纯”内容(因此保证仅由其范围拥有)。 T 的所有嵌套字段也是如此。这样就不需要生命周期说明符来转移所有权。 i32 实现了哪些特征,而我的通用类型 T 没有实现以防止错误 fn 编译?

fn error<T: Send+Sized>(mut data: Vec<T>)->Receiver<T>{
    let (s, r) = channel();
    std::thread::spawn(move ||{
        while let Some(nextthing) = data.pop(){
            s.send(nextthing);
        }
    });
    r
}

相对于

fn thisworks(mut data: Vec<i32>)->Receiver<i32>{
    let (s, r) = channel();
    std::thread::spawn(move ||{
        while let Some(nextthing) = data.pop(){
            s.send(nextthing);
        }
    });
    r    
}

错误:我只想让它像 i32 一样工作:所有权只是干净地转移,没有问题(可能与 Primitive 类型和 i32 的复制特征有关?)

rror[E0310]: the parameter type `T` may not live long enough
 --> src/main.rs:7:5
  |
5 | fn error<T: Send+Sized>(mut data: Vec<T>)->Receiver<T>{
  |          -- help: consider adding an explicit lifetime bound `T: 'static`...
6 |     let (s, r) = channel();
7 |     std::thread::spawn(move ||{
  |     ^^^^^^^^^^^^^^^^^^
  |
note: ...so that the type `[closure@src/main.rs:7:24: 11:6 data:std::vec::Vec<T>, s:std::sync::mpsc::Sender<T>]` will meet its required lifetime bounds
 --> src/main.rs:7:5
  |
7 |     std::thread::spawn(move ||{
  |     ^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0310`.
error: Could not compile `playground`.

游乐场链接是https://play.rust-lang.org/?version=nightly&mode=release&edition=2018&gist=117113384490f15bb33ff8f749661769

【问题讨论】:

  • Sized 是泛型的默认绑定;你不需要明确地写出来。

标签: generics rust


【解决方案1】:

这与类型无关,而与类型的生命周期有关。

编译器错误很明显。您需要的唯一更改是这一行:

fn error<T: Send+Sized+'static>(mut data: Vec<T>)->Receiver<T>{

这个添加'static是一个额外的要求,类型不能是临时的;即它必须在程序的生命周期内定义。这并不意味着对象本身必须具有'static 生命周期,而只是类型。

【讨论】:

  • 是否有更多关于类型拥有生命周期意味着什么的信息?或者类型是短暂的意味着什么?我假设+'static 意味着T 的实例可能包含的任何引用都必须在程序的生命周期内有效。
  • 我当然可以为您找到大量 issues,这会导致问题。让我们看看我能不能找到真正完整描述的文档。
  • Found it。在这种情况下,'static 施加的确切条件是类型 T 内的所有引用都必须比 'static 寿命长(这是有道理的,因为它会跨越线程边界)
  • 那么 i32 是否有一个“静态生命周期”?
  • 一个i32 不包含引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2021-04-06
相关资源
最近更新 更多