【发布时间】: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`.
【问题讨论】:
-
Sized是泛型的默认绑定;你不需要明确地写出来。