0

I'm using the statrs crate for some statistical work. There is a part where I sample data from various distributions and I would like to write that code only once. However, I am using several different distribution functions.

My idea is something like this:

let norm = Normal::new(x,y);
let lognorm: LogNormal::new(a,b);

sample(norm);
sample(lognorm);

fn sample (d: Distribution) {
   for i in 1..100 {
      let a = d.sample();
   }
}

but since Traits are not interfaces, it isn't quite so simple. Rust seems to require me to specify "Normal" and not "Distribution".

There are some other questions touching on this question, but none of them seems to me to answer to my problem. I understand that traits are not interfaces, what I don't get is how to basically pass a reference to a trait with different implementations into further processing.

Tom
  • 2,688
  • 3
  • 29
  • 53
  • @FrenchBoiethios I saw that question, but it doesn't solve my problem or maybe I just really don't understand this part of rust. – Tom Apr 23 '19 at 18:14
  • 2
    Read the part about dispatches. TLDR: you should use generics: `impl Distribution` – Boiethios Apr 23 '19 at 18:20

0 Answers0