Here is a link to this example in Rust playground
我正在创造两个特征。一个特征使用另一个特征作为关联类型。相关特征扩展为FromStr
:
trait Behaviour where Self: FromStr {}
trait AnotherBehaviour {
type Assoc: Behaviour;
}
我可以分别为Derp
和AnotherDerp
实现这些特征,记住为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,
但我如何约束Behaviour
或AnotherBehaviour
特征以要求FromStr::Err
实施Debug
?我无法弄清楚语法。
我试过了
trait Behaviour: FromStr
where
<Self as FromStr>::Err: Debug
和
trait Behaviour: FromStr
where
Self::Err: Debug