Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Last active November 23, 2018 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save souenzzo/6e5f5e117985e0bc3dd92537e355babd to your computer and use it in GitHub Desktop.
Save souenzzo/6e5f5e117985e0bc3dd92537e355babd to your computer and use it in GitHub Desktop.
use std::ops::Add;
use std::ops::Div;
trait IAverage<T> {
fn new(a: T) -> Self;
fn combine(self, b: Self) -> Self;
fn result(self) -> T;
}
// trait Number: Sized
trait Number {
fn one() -> Self;
fn add(self, a: Self) -> Self;
fn div(self, a: Self) -> Self;
}
struct Average<T> {
sum: T,
count: T,
}
impl<T> IAverage<T> for Average<T> where T: Number {
fn new(a: T) -> Average<T> {
return Average { sum: a, count: Number::one() };
}
fn combine(self, a: Average<T>) -> Average<T> {
return Average {
sum: self.sum.add(a.sum),
count: self.count.add(a.count),
};
}
fn result(self) -> T {
return self.sum.div(self.count);
}
}
impl Number for f64 {
fn one() -> f64 { return 1.0; }
fn add(self, a: Self) -> Self { return Add::add(self, a); }
fn div(self, a: Self) -> Self { return Div::div(self, a); }
}
fn main() {
let a = Average::new(5.0);
let b = Average::new(3.0);
let c = a.combine(b);
let x = c.result();
println!("Hello, world! {}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment