multithreading - 如何将通用 T 发送到另一个线程?

标签 multithreading generics rust traits parametric-polymorphism

如何发送通用T ?
我尝试发送通用 T到另一个线程,但我得到:

error[E0308]: mismatched types
  --> src/main.rs:23:22
   |
23 |             t1.merge(Element(vec![3]));
   |                      ^^^^^^^^^^^^^^^^ expected associated type, found struct `Element`
   |
   = note: expected associated type `<T as Join>::Item`
                       found struct `Element`
   = help: consider constraining the associated type `<T as Join>::Item` to `Element`
完整代码:
trait Join {
    type Item;
    fn merge(&mut self, other: Self::Item);
}

#[derive(Debug, Default)]
struct Element(Vec<u8>);

impl Join for Element {
    type Item = Element;
    fn merge(&mut self, mut other: Self::Item) {
        self.0.append(&mut other.0);
    }
}

fn work<T>()
where
    T: Default + Join + Send + Sync + 'static,
{
    let (sender, receiver) = std::sync::mpsc::channel::<(T)>();
    std::thread::spawn(move || {
        while let (mut t1) = receiver.recv().unwrap() {
            t1.merge(Element(vec![3]));
        }
    });

    loop {
        let mut t1 = T::default();
        sender.send(t1);
        std::thread::sleep(std::time::Duration::from_secs(5));
    }
}

fn main() {
    // works!
    let mut e = Element(vec![1]);
    e.merge(Element(vec![2]));

    // bad!
    work::<Element>();
}
Playground link

最佳答案

当你使用泛型时,你让调用者决定你的泛型函数必须使用哪些类型。
您的示例中的这一行 t1.merge(Element(vec![3]));无效,因为它假定 T = Element但是调用者可以从无限多种可能的 T 类型中进行选择。在哪里 T != Element这就是编译器提示的原因。
要使您的函数完全通用,您必须执行添加 Default 之类的操作。绑定(bind)到<T as Join>::Item在函数签名中,然后将违规行更改为 t1.merge(<T as Join>::Item::default()); .
更新的工作注释示例:

use std::fmt::Debug;

trait Join {
    type Item;
    fn merge(&mut self, other: Self::Item);
}

#[derive(Debug)]
struct Element(Vec<u8>);

// updated Default impl so we can observe merges
impl Default for Element {
    fn default() -> Self {
        Element(vec![1])
    }
}

impl Join for Element {
    type Item = Element;
    fn merge(&mut self, mut other: Self::Item) {
        self.0.append(&mut other.0);
    }
}

fn work<T>() -> Result<(), Box<dyn std::error::Error>>
where
    T: Default + Join + Send + Sync + Debug + 'static,
    <T as Join>::Item: Default, // added Default bound here
{
    let (sender, receiver) = std::sync::mpsc::channel::<T>();
    std::thread::spawn(move || {
        while let Ok(mut t1) = receiver.recv() {
            // changed this to use Default impl
            t1.merge(<T as Join>::Item::default());

            // prints "Element([1, 1])" three times
            println!("{:?}", t1);
        }
    });

    let mut iterations = 3;
    loop {
        let t1 = T::default();
        sender.send(t1)?;
        std::thread::sleep(std::time::Duration::from_millis(100));
        iterations -= 1;
        if iterations == 0 {
            break;
        }
    }

    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // works!
    let mut e = Element(vec![1]);
    e.merge(Element(vec![2]));

    // now also works!
    work::<Element>()?;

    Ok(())
}
playground

关于multithreading - 如何将通用 T 发送到另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65995021/

相关文章:

rust - 循环中看似不一致的借用检查器行为

c++ - Visual C++ 中的线程

multithreading - 带有警报的 Perl 线程

c# - TaskFactory.Tasks 中 BlockingCollection.GetConsumingEnumerable() 集合的 Parallel.ForEach 和 foreach 循环

swift - 任何类型的通用类型

java - 我的问题是关于通过 java 泛型添加不同包装类的数组

rust - Rust 的设计者选择符号 !/&&/|| 的原因是什么?而不是单词 not/and/or?

java - 同时函数调用

c# - 泛型和集合继承

casting - 转换相同底层类型的枚举变体