syntax - 如何在非拥有特征上约束关联类型?
问题描述
我正在创造两个特征。一个特征使用另一个作为关联类型。相关特征扩展FromStr
:
trait Behaviour where Self: FromStr {}
trait AnotherBehaviour {
type Assoc: Behaviour;
}
我可以分别为Derp
和实现这些特征AnotherDerp
,记住实现FromStr
for 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
orAnotherBehaviour
特征要求FromStr::Err
实现Debug
?我无法弄清楚语法。
我努力了
trait Behaviour: FromStr
where
<Self as FromStr>::Err: Debug
和
trait Behaviour: FromStr
where
Self::Err: Debug
解决方案
推荐阅读
- php - 当试图要求一个确实存在的文件时 PHP 给出错误
- python - 在python中具有相似名称时修改xml元素
- mysql - 将两个生成的列相加
- c# - LINQ 按 x 天数分组
- c# - 方法'System.Web.Mvc.ActionResult PlaceCheckout(Int32,Int32)的不可为空类型'System.Int32'的参数'libraryId'的空条目
- c# - 多次注册同一个服务的目的是什么?
- javascript - Pusher (React) 在 4 小时不活动后自动断开应用程序(401 错误)
- python - App.route 在 Flask 中不适用于一种方法
- wordpress - Divi Visual Builder 越野车
- r - 将基因位置映射到染色体坐标