我想SomeType
取出Result<Vec<Data<&SomeType>>>
,然后通过通道传递它,但我失败了:
pub fn read(result: Result<Vec<Data<&SomeType>>, ()>, tx: mpsc::Sender<SomeType>) {
if let Ok(datas) = result {
for data in datas.iter() {
let actual_data = data.value();
let some_type_instance = SomeType { k: 1 };
tx.send(some_type_instance); // works
tx.send(**actual_data); // errors
}
}
}
错误:
error[E0507]: cannot move out of `**actual_data` which is behind a shared reference
--> src/main.rs:40:21
|
40 | tx.send(**actual_data);
| ^^^^^^^^^^^^^ move occurs because `**actual_data` has type `SomeType`, which does not implement the `Copy` trait
似乎tx
没有正确地取得所有权。尽管实现Copy
trait onSomeType
可以消除错误,但我不确定是否Copy
或Clone
会降低性能。我正在努力解决它,但找不到正确的方法来解决它。
以下是重新生成错误的完整代码。
use std::result::Result;
use std::sync::mpsc;
pub struct SomeType {
k: i32,
}
pub struct Data<D> {
value: D,
}
impl<D> Data<D> {
pub fn value(&self) -> &D {
&self.value
}
}
pub fn main() {
let a = SomeType { k: 1 };
let b = SomeType { k: 2 };
let c = SomeType { k: 3 };
let A = Data { value: &a };
let B = Data { value: &b };
let C = Data { value: &c };
let datas = vec![A, B, C];
let result = Ok(datas);
let (tx, rx) = mpsc::channel();
read(result, tx);
}
pub fn read(result: Result<Vec<Data<&SomeType>>, ()>, tx: mpsc::Sender<SomeType>) {
if let Ok(datas) = result {
for data in datas.iter() {
let actual_data = data.value();
let some_type_instance = SomeType { k: 1 };
tx.send(some_type_instance); // this line works
tx.send(**actual_data); // this line errors
}
}
}