对具有不同参数的特征的new()方法

jay*_*elm 3 traits rust

我正在尝试使用不同的内部参数进行各种实现:

pub trait ERP {
    fn new() -> Self;
    fn sample(&self) -> f64;
}

pub struct Bernoulli {
    p: f64
}

impl ERP for Bernoulli {
    fun new(p: f64) -> Bernoulli {
        Bernoulli { p: p }
    }

    fun sample(&self) -> f64 { self.p } // Filler code
}

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

impl ERP for Gaussian {
    fun new(mu: f64, sigma: f64) -> Gaussian {
        Gaussian { mu: mu, sigma: sigma }
    }

    fun sample(&self) -> f64 { self.mu } // Filler code
}
Run Code Online (Sandbox Code Playgroud)

但我当然得到了

error: method new` has 1 parameter but the declaration in trait
`erp::ERP::new` has 0
Run Code Online (Sandbox Code Playgroud)

因为我必须在特征中指定固定数量的参数.

我也不能放弃new这个特性,因为那样

error: method `new` is not a member of trait `ERP`
Run Code Online (Sandbox Code Playgroud)

我的动机是想暴露的ERP接口保持一致,除了new方法,因为每个分配的必要参数取决于它的实现背后的独特的数学.有没有解决方法?

A.B*_*.B. 8

不要使new功能成为特征的一部分.不支持具有可变数量的输入参数的函数.

  • 你好@ab,我认为你现在可以在特征中使用“new”静态方法:https://doc.rust-lang.org/rust-by-example/trait.html (4认同)