I'm trying to make a trait with various implementations with different internal 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
}
But of course I get
error: method new` has 1 parameter but the declaration in trait
`erp::ERP::new` has 0
since I must specify a fixed number of arguments in the trait.
I also can't leave new
out of the trait, since that gives
error: method `new` is not a member of trait `ERP`
My motivation is that I want the exposed ERP interface to stay consistent except for the new
method, since each distribution's required parameters are dependent on the unique mathematics behind its implementation. Are there any workarounds?
Don't make the new
function part of the trait. Functions with variable number of input arguments are not supported.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With