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

Oka*_*rin 5 traits rust

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

pub trait Test<W> {
    type Error;

    fn do_sth(&mut self) -> Result<W, Self::Error>;
}
Run Code Online (Sandbox Code Playgroud)

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

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

操场

Cer*_*rus 9

当您需要向外部类型添加方法时,唯一的选择是使用扩展特征。这意味着您可以使用您需要的任何方法定义自己的特征,并为您需要的类型实现它。

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

操场

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