具有不同参数的特征的 new() 方法
new() method on traits with varying parameters
我正在尝试使用具有不同内部参数的各种实现来创建特征:
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 接口保持一致 除了 对于 new
方法,因为每个分布的必需参数都取决于背后的独特数学它的实施。有什么解决方法吗?
不要将 new
函数作为特征的一部分。不支持输入参数数量可变的函数。
我正在尝试使用具有不同内部参数的各种实现来创建特征:
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 接口保持一致 除了 对于 new
方法,因为每个分布的必需参数都取决于背后的独特数学它的实施。有什么解决方法吗?
不要将 new
函数作为特征的一部分。不支持输入参数数量可变的函数。