如何定义一个结构,该结构是发送+同步并持有 io::Write 成员



我有一个结构,需要impl给定的特征,该特征本身Send + Sync ;我还希望结构包含任何io::Write的泛型类型(但不一定是Send + Sync)。我完全不知道如何制定它。

比方说

struct Foobar<T> {
    stream: T,
}
impl<T> Foobar<T>
    where T: io::Write
{
    pub fn new(stream: T) -> Foobar<T> {
        Foobar { stream: stream }
    }
}

这本来就不Send + Sync,所以我们可以(不能)做

struct Foobar<T> {
    stream: Arc<Mutex<T>>,
}
impl<T> Foobar<T>
    where T: io::Write
{
    pub fn new(stream: T) -> Foobar<T> {
        Foobar { stream: Arc::new(Mutex::new(stream)) }
    }
}
impl<T> mycrate::TraitRequiringSendSync for Foobar<T> {
    fn write(the_msg: &str) {
        self.stream.lock().unwrap().write(...)
    }
}

我完全不知道如何表述io::Write stream的内部类型,并且Foobar的整体implSend + Sync

基本上,你只需要约束T Write + Send

use std::sync::{Arc, Mutex};
use std::io::Write;
//This is the important bit
struct Foobar<T: Write + Send> {
    stream: Arc<Mutex<T>>,
}
impl<T: Write + Send> Foobar<T>
{
    pub fn new(stream: T) -> Foobar<T> {
        Foobar { stream: Arc::new(Mutex::new(stream)) }
    }
}
trait Test: Write + Send {}
//verify that Foobar is Send + Sync
impl<T: Write + Send> Test for Foobar<T> { }