如何限制非拥有特征的关联类型?

时间:2018-06-09 16:02:20

标签: syntax rust traits associated-types

Here is a link to this example in Rust playground

我正在创造两个特征。一个特征使用另一个特征作为关联类型。相关特征扩展为FromStr

trait Behaviour where Self: FromStr {}
trait AnotherBehaviour {
    type Assoc: Behaviour;
}

我可以分别为DerpAnotherDerp实现这些特征,记住为FromStr实施Derp

struct Error {}
struct Derp {}
struct AnotherDerp {}

impl Behaviour for Derp {}
impl FromStr for Derp {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s { "derp" => Ok(Derp{}), _ => Err(Error {}) }
    }
}

impl AnotherBehaviour for AnotherDerp {
    type Assoc = Derp;
}

现在我想创建一个使用封装特征的泛型函数。

fn run<T: AnotherBehaviour>() {
    let derp = T::Assoc::from_str("derp").expect("expected derp");
}

fn main() {
    run::<AnotherDerp>();
}

我收到错误:

note: the method `expect` exists but the following trait bounds were not satisfied:
       `<<T as AnotherBehaviour>::Assoc as std::str::FromStr>::Err : std::fmt::Debug`

我为Debug类型实施Error

#[derive(Debug)]
struct Error {}

但这不会起作用,因为我实际上需要限制这种特性。

我知道我可以用

约束泛型函数
where
    <T::Assoc as FromStr>::Err: Debug,

但我如何约束BehaviourAnotherBehaviour特征以要求FromStr::Err实施Debug?我无法弄清楚语法。

我试过了

trait Behaviour: FromStr
where
     <Self as FromStr>::Err: Debug

trait Behaviour: FromStr
where
    Self::Err: Debug

0 个答案:

没有答案