gpt4 book ai didi

新类型的 Rust 特征

转载 作者:行者123 更新时间:2023-12-03 11:26:22 28 4
gpt4 key购买 nike

假设我定义了一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com