rust - 我可以有条件地提供特征函数的默认实现吗?
问题描述
我有以下特点:
trait MyTrait {
type A;
type B;
fn foo(a: Self::A) -> Self::B;
fn bar(&self);
}
还有其他类似的功能bar
必须始终由 trait 的用户实现。
我想给出foo
一个默认实现,但只有当 type A = B
.
伪锈代码:
impl??? MyTrait where Self::A = Self::B ??? {
fn foo(a: Self::A) -> Self::B {
a
}
}
这是可能的:
struct S1 {}
impl MyTrait for S1 {
type A = u32;
type B = f32;
// `A` is different from `B`, so I have to implement `foo`
fn foo(a: u32) -> f32 {
a as f32
}
fn bar(&self) {
println!("S1::bar");
}
}
struct S2 {}
impl MyTrait for S2 {
type A = u32;
type B = u32;
// `A` is the same as `B`, so I don't have to implement `foo`,
// it uses the default impl
fn bar(&self) {
println!("S2::bar");
}
}
这在 Rust 中可能吗?
解决方案
您可以通过引入冗余类型参数在特征定义本身中提供默认实现:
trait MyTrait {
type A;
type B;
fn foo<T>(a: Self::A) -> Self::B
where
Self: MyTrait<A = T, B = T>,
{
a
}
}
可以为单个类型覆盖此默认实现。但是,专用版本将从 trait 的定义中继承 trait 绑定,foo()
因此您只能在以下情况下实际调用该方法A == B
:
struct S1;
impl MyTrait for S1 {
type A = u32;
type B = f32;
fn foo<T>(a: Self::A) -> Self::B {
a as f32
}
}
struct S2;
impl MyTrait for S2 {
type A = u32;
type B = u32;
}
fn main() {
S1::foo(42); // Fails with compiler error
S2::foo(42); // Works fine
}
Rust 还有一个不稳定的 impl 专业化特性,但我不认为它可以用来实现你想要的。
推荐阅读
- python - 如何找到屏幕上某个像素的RBG颜色?
- sql-server - 如何在我的sql查询中实现多个条件
- java - 缺少 JavaFX 运行时组件,需要从 java -jar myprogram.jar 运行此应用程序
- flutter - TextField中的标签文本不会居中?
- css - 包裹在 100vh 中时,react-scrollable-anchor 停止工作
- c# - Build LINQ Lambda Expression with contains method for enum property with list of int
- javascript - 如何在提交之前验证输入?
- java - 如何将 post 方法与 spring 数据休息过程一起使用?
- sql - 使用 Tableau 中的“in”子句将参数添加到自定义 sql 查询
- javascript - 无法在 nestjs 应用程序中设置配置文件