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

问题描述 投票:3回答:2

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

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

rust traits
2个回答
1
投票

您想要以下吗?

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

我是在编译器提示“必须指定关联类型Error的值”之后提出的。


0
投票

当您需要向外部类型添加方法时,唯一的选择是使用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

您可以将相同的想法应用于任何外部特征。

© www.soinside.com 2019 - 2024. All rights reserved.