【发布时间】:2019-04-13 19:23:00
【问题描述】:
我有以下特点:
trait MyTrait {
type A;
type B;
fn foo(a: Self::A) -> Self::B;
fn bar(&self);
}
还有其他函数,例如 bar,必须始终由 trait 的用户实现。
我想给foo 一个默认实现,但仅限于A = B 类型。
伪 Rust 代码:
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 中可能吗?
【问题讨论】:
-
在尝试回答时,我遇到了another question,这可能很有趣。
-
不接受
self(或引用它)或返回Self的特征函数是否有意义? -
@Cerberus 我想不会,但这只是简化的示例。我将对其进行编辑以使其更有意义。
标签: rust