我只是构建了一个具有 2 个函数的特征
Bar
(带有实现的 alpha()
和仅带有接口的 beta()
),并且我希望实现 Bar
的结构只实现 beta()
,并且永远不要实现自己的 alpha()
.
有什么方法可以阻止另一个结构实现自己的
alpha()
?
trait Bar {
fn alpha(&self) {
println!("you should never implement this function on your own.");
}
fn beta(&self);
}
struct Foo {}
impl Bar for Foo {
fn alpha(&self) {
println!("how do I trigger an error here when a struct implement it's own alpha()?");
}
fn beta(&self) {
println!("implement beta() for Foo");
}
}
您可以通过将您的特征分成两部分,并使用默认方法为该特征提供一揽子实现来做到这一点。
pub trait Beta {
fn beta(&self);
}
pub trait Alpha: Beta {
fn alpha(&self) {
// Default impl
}
}
// Because of this blanket implementation,
// no type can implement `Alpha` directly,
// since it would conflict with this impl.
// And you cannot implement `Alpha` without `Beta`,
// since `Beta` is its _supertrait_.
impl<T: Beta> Alpha for T {}
struct Foo;
impl Beta for Foo {
fn beta(&self) {
// Impl
}
}
// If you uncomment this you will have a compile error,
// because of the conflicting implementations of Alpha for Foo
// (conflicts with the blanket implementation above)
//
// impl Alpha for Foo {
// fn alpha(&self) {
// // override impl
// }
// }
pub fn bar<T: Alpha>(_: T) {}
pub fn baz() {
bar(Foo);
}