假设我定义了一个 Group
所有组操作的特征。是否可以创建一个包装器AGroup
超过 Group
无需手动派生所有操作?
基本上,我想要这个:
#[derive (Copy, Debug, Clone, Eq, PartialEq, Group)] // How could I derive Group here as well?
struct AGroup<G: Group>(G);
没有所有这些样板:impl<G: Group> Add for AGroup<G>{
type Output = AGroup<G>;
fn add(self, other: Self) -> Self {
AGroup(self.0 + other.0)
}
}
impl<G: Group> Neg for AGroup<G>{
type Output = AGroup<G>;
fn neg(self) -> Self {
AGroup(-self.0)
}
}
...
最佳答案
您也可以只创建一个公开内部对象接口(interface)的方法:
pub trait Group {
fn foo(self: &Self){
println!("Called from group")
}
}
#[derive (Copy, Debug, Clone, Eq, PartialEq)] // How could I derive Group here as well?
pub struct AGroup<G: Group>(G);
impl<G: Group> AGroup<G> {
pub fn inner(&self) -> &impl Group {
&self.0
}
}
pub struct Test {}
impl Group for Test {}
fn main( ) {
let a = AGroup( Test {} );
a.inner().foo();
}
Playground
关于新类型的 Rust 特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66545506/