我希望能够说“此特征是该 super 特征的一个子代,因此它应该实现其所有功能”。
问题是trait X: Y {}
意味着必须实现Y
和X
。我只希望实现X
,但要确保所有功能都与Y
匹配。
Playground link
trait GeneralA {
fn get_x() -> String;
}
// Issue: cannot do `SpecificA : GeneralA` without also implementing GeneralA, but I want to enforce only having specific implementations, no general or default functions are possible.
trait SpecificA {
fn get_x() -> String;
}
trait SpecificB {
fn get_x() -> String;
}
struct S1;
impl SpecificA for S1 {
fn get_x() -> String {
"SpecificA->get_x".to_string()
}
}
impl SpecificB for S1 {
fn get_x() -> String {
"SpecificB->get_x".to_string()
}
}
fn main() {
dbg!(<S1 as SpecificA>::get_x());
dbg!(<S1 as SpecificB>::get_x());
}
我要在类型系统中描述的内容:SpecificX
特征。 GeneralA
特性。 SpecificX
特性应具有GeneralA
特性的所有功能。 问题是Rust希望我实现
GeneralA
和SpecificX
。如何在类型系统中执行此操作?
最佳答案
如果未实现特征的“通用”版本,而未实现“特定”版本,则它们之间的关系不能成为超特征关系。听起来您想要的是通用特征,以及一些用于对其进行参数化的标记类型。
trait HasX<T> {
fn get_x() -> String;
}
struct A {}
impl HasX<A> for S1 {
fn get_x() -> String {
"SpecificA->get_x".to_string()
}
}
struct B {}
impl HasX<B> for S1 {
fn get_x() -> String {
"SpecificB->get_x".to_string()
}
}
无需实例化A
和B
¹–它们仅存在于参数化HasX
的情况下。 (根据问题的性质,可能已经有一些类型可用于参数化HasX
;在这种情况下,您无需创建新的类型。)¹可以使用空的
struct
(例如enum
)代替空的enum A {}
来强制执行永不实例化的方法,尽管这样做会牺牲它们为您提供的一些灵活性。
关于types - 如何在不执行功能的情况下强制执行 super 特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64406203/