【问题标题】:Methods shared among structs结构之间共享的方法
【发布时间】:2015-07-02 13:10:09
【问题描述】:

这里是 Rust 新手,为我的幼稚道歉。

我想定义一些概率分布,它们显然具有不同的参数。但是“接口”(正如我在 Java 中所知道的那样)应该是相同的。在最基本的层面上,每个发行版都应该有一个sample 和一个sample_many 方法。所以我实现了一个特征:

pub trait ERP<T> {
    fn sample(&self) -> T;
    fn sample_many(&self, i: isize) -> Vec<T>;
}

然后可以创建一个特定的分布:

pub struct Bernoulli {
    pub p: f64
}

impl ERP<bool> for Bernoulli {
    fn sample(&self) -> bool {
        rand::random::<f64>() < self.p
    }

    fn sample_many(&self, i: isize) -> Vec<bool> {
        (0..i).map(|_| self.sample()).collect()
    }
}

我的问题是 sample_many 方法,特别是。无论分布类型如何,此方法都是相同的代码,例如

pub struct Gaussian {
    pub mu: f64,
    pub sigma: f64
}

impl ERP<f64> for Gaussian {
    fn sample(&self) -> f64 {
        // Code unique to each distribution
    }

    fn sample_many(&self, i: isize) -> Vec<f64> {
        (0..i).map(|_| self.sample()).collect() // Code reuse??
    }
}

所以在这里复制方法是非常多余的。有没有办法解决这个问题?

【问题讨论】:

  • @ker 我的目的不是创建一个可编译的示例,而只是一个通用问题的示例,因此在Gaussian 中省略了sample
  • rust 对于这种情况有 unimplemented!() 宏。您的代码将编译,但没有任何用处。你可以在is.gd/WwsBW2看到这个
  • 对于非常相似的代码,有时实现宏是有意义的。不过,我认为@ker 的默认实现在这里是最合适的。 (见宏观问题:stackoverflow.com/questions/31082179/…

标签: struct rust traits


【解决方案1】:

您可以为特征定义中的任何函数创建默认实现。它仍然可以被实现者覆盖

pub trait ERP<T> {
    fn sample(&self) -> T;
    fn sample_many(&self, i: isize) -> Vec<T> {
        (0..i).map(|_| self.sample()).collect()
    }
}

【讨论】:

  • 如果sample_many 需要访问strut字段怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 2018-07-30
  • 2016-06-05
  • 2018-03-25
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多