新类型的 Rust 特征

标签 rust traits

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

相关文章:

rust - 使用 LD.LLD 链接 Rust 二进制文件

rust - mio 负载较小的简单 TCP 服务器出现“连接被对等重置”错误

python - 在 Item 中使用 HasTraits 对象时,从多个 View 中进行选择

asynchronous - 有没有办法等待返回Result <T,E>而不是T?

rust - 无法在tokio::fs::File上调用poll_read

rust - 是否可以通过特征将值存储在结构中?

rust - 添加和+之间的区别?

rust - 跨多个特征借用数据时如何编写适当的通用函数签名

python - 使用属性或特征处理程序设置因变量之间的区别

rust - "borrowed value does not live long enough"trie插入错误