Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

rust - Struct with integer or float

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.

question from:https://stackoverflow.com/questions/65893341/struct-with-integer-or-float

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...