Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new() method on traits with varying parameters

Tags:

rust

traits

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?

like image 413
jayelm Avatar asked Jul 02 '15 14:07

jayelm


1 Answers

Don't make the new function part of the trait. Functions with variable number of input arguments are not supported.

like image 168
A.B. Avatar answered Nov 23 '22 06:11

A.B.