我正在尝试将扩展方法添加到不同包装箱中的特征中。此特征具有指定的关联类型。
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()
}
}
您想要以下吗?
impl<E> dyn Test<u8, Error = E> {
fn use_do_sth(&mut self) -> Result<u8, E> {
self.do_sth()
}
}
我是在编译器提示“必须指定关联类型Error
的值”之后提出的。
当您需要向外部类型添加方法时,唯一的选择是使用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);
}
}
您可以将相同的想法应用于任何外部特征。