首页 > 解决方案 > 如何在非拥有特征上约束关联类型?

问题描述

这是 Rust 游乐场中此示例的链接

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

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

我可以分别为Derp和实现这些特征AnotherDerp,记住实现FromStrfor 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,

但是我怎样才能限制BehaviourorAnotherBehaviour特征要求FromStr::Err实现Debug?我无法弄清楚语法。

我努力了

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

trait Behaviour: FromStr
where
    Self::Err: Debug

标签: syntaxrusttraitsassociated-types

解决方案


推荐阅读