1

I'm new to Rust and currently reading about structs. The code below is just a simple test of mine and I was wondering how to allow any numeric value as a property r of the Circle structure. I want it to be able to store an integer or a float.

I would assume overloading but not sure. Also from what I've searched online there are some crates num and num-traits but I'm unsure how to use them, unless I missed the doscs section.

use std::f64::consts::PI;

trait Area {
    fn calculate_area(self) -> f64;
}

struct Circle {
    r:f64
}

impl Area for Circle {
    fn calculate_area(self) -> f64 { 
        PI * self.r * self.r
    }
}

fn main() {

    let c = Circle { r: 2.5 };

    println!("The area is {}", c.calculate_area())
    
}

I would prefer a solution without having to include another crate.

1 Answer 1

1

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

I would even make T in Arena<T> an associated type: for any given type, you will ever have one implementation of Arena. Plus you can use the FloatConst trait to use directly T::PI.
The use of T::from_f64(PI) is somewhat dubious, since it may cause the result to be off by a lot more than the precision of T (for instance, 9π is closer to 28 than 27). But it's not super clear what the "correct" behavior should be in this case, so shrug

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.