This is quite easy using the num_traits
crate:
use num_traits::{FromPrimitive, Num};
use std::f64::consts::PI;
trait Area<T>
where
T: Num + FromPrimitive + Copy,
{
fn calculate_area(self) -> T;
}
struct Circle<T>
where
T: Num + FromPrimitive + Copy,
{
r: T,
}
impl<T> Area<T> for Circle<T>
where
T: Num + FromPrimitive + Copy,
{
fn calculate_area(self) -> T {
T::from_f64(PI).unwrap() * self.r * self.r
}
}
fn main() {
let c = Circle { r: 2.5 };
println!("Float: The area is {}", c.calculate_area());
let ci = Circle { r: 3 };
println!("Integer: The (approxmiate) area is {}", ci.calculate_area());
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…