如何将扩展方法添加到具有位于不同板条箱中的关联类型的特征?

How can I add extension methods to a trait with associated types lying in a different crate?

我正在尝试向不同板条箱中的特征添加扩展方法。 此特征具有指定的关联类型。

pub trait Test<W> {
    type Error;

    fn do_sth(&mut self) -> Result<W, Self::Error>;
}

为什么无法添加使用关联类型的方法 Error

impl dyn Test<u8> {
    fn use_do_sth(&mut self) -> Result<u8: Self::Error> {
        self.do_sth()
    }
}

playground

你想要以下吗?

impl<E> dyn Test<u8, Error = E> {
    fn use_do_sth(&mut self) -> Result<u8, E> {
        self.do_sth()
    }
}

我根据编译器的提示 "the value of the associated type Error must be specified".

想到了这个

当你需要给外部类型添加一个方法时,唯一的选择就是使用extension traits。这意味着您定义自己的特征,使用您需要的任何方法,并为您需要的类型实现它。

当你需要为所有类型添加一个方法来实现一些外部特征时,你可以使用相同的模式,但不要直接列出类型,只需使用特征绑定:

use std::fmt::Debug;

// This is an extension trait.
// You can force all its implementors to implement also some external trait,
// so that two trait bounds essentially collapse into one.
trait HelperTrait: Debug {
    fn helper_method(&mut self);
}

// And this is the "blanket" implementation,
// covering all the types necessary.
impl<T> HelperTrait for T where T: Debug {
    fn helper_method(&mut self) {
        println!("{:?}", self);
    }
}

Playground

如您所愿,同样的想法可以应用于任何外部特征。