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

2024-02-19

我正在尝试使用具有不同内部参数的各种实现来创建一个特征:

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
}

但我当然明白

error: method new` has 1 parameter but the declaration in trait
`erp::ERP::new` has 0

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

我也无法离开new出于特征,因为这给出了

error: method `new` is not a member of trait `ERP`

我的动机是希望公开的 ERP 接口保持一致except为了new方法,因为每个分布所需的参数都取决于其实现背后的独特数学。有什么解决方法吗?


不要使new功能是特质的一部分。不支持具有可变数量输入参数的函数。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有不同参数的特征的 new() 方法 的相关文章

随机推荐