rust - 为通用特征实现特征
问题描述
在 Rust 中,如何为通用 trait 实现 Trait?
trait One<S> {}
trait Two {}
// fails because S isn't contrained
impl<S, T> Two for T where T: One<S> {}
为了澄清,我试图为BitAnd
通用特征提供Select
特征。
struct Thing<S> {
field: S,
}
trait Select<S> {
fn select(&self, thing: &Thing<S>) -> bool;
}
struct SelectUnion<S> (Box<dyn Select<S>>, Box<dyn Select<S>>);
// fails because S isn't contrained
impl<S, T> std::ops::BitAnd for T where T: Select<S> {
type Output = SelectUnion<S>;
fn bitand(self, rhs: Self) -> Self::Output {
SelectUnion(Box::new(self), Box::new(rhs))
}
}
解决方案
不可能,原因是它会模棱两可。
想想这样的情况:
struct A;
impl One<u16> for A {}
impl One<u32> for A {}
这两个One
实现中的哪一个Two
将基于?两者都满足一揽子Two
实现的先决条件,但Two
对于任何类型都只能实现一次。就像您要提供两个单独的impl Two for A
块一样。
问题澄清后编辑:
以上仍然成立,但您可能想尝试是否可以将 Select 变成一个类型,可能通过将它变成一个可选择的包装器。
推荐阅读
- excel - 将变量从用户窗体传递到模块
- git - OpenSSL 和原生 windows 安全通道库有什么区别
- sql-server - 实体框架和 JSON.NET 序列化
- spring - Spring Boot 中用于 Amazon Aurora Serverless 的数据 API
- emacs - 重映射邪恶模式写入
- swift - Xcode 对“绑定”的期望是什么
“占位符? - java - 从带有处理指令的 XML 文件中读取并写入另一个输出文件
- python - 如何将固定数字添加到文件名的整数部分?
- python - 如何将文本中的一行视为整数?
- android - Xamarin Forms Android - 将操作系统时间更改为较早日期后应用程序无法启动