Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor shared methods of f32 and f64 into new Float trait #3609

Open
amab8901 opened this issue Apr 10, 2024 · 1 comment
Open

Refactor shared methods of f32 and f64 into new Float trait #3609

amab8901 opened this issue Apr 10, 2024 · 1 comment

Comments

@amab8901
Copy link

I'm trying to create a library that rounds float types (f32 and f64) to a specified number of digits by calling on the "round()" function along with some other operations. Right now it's pretty inconvenient to make such an implementation. I tried using type_name but it gets kinda messy:

#![allow(clippy::let_and_return)]

pub mod round_float {

    use std::any::type_name;

    use anyhow::Result;

    use cast::f64;

    pub fn round_float<T>(full_float: T, digits: u32) -> Result<f64> {
        let type_name = type_name_of(full_float);
        if type_name == "f32" || type_name == "f64" {
            return Err(anyhow::Error::msg("Expected `f32` or `f64`."));
        }

        let float64 = f64::from(full_float);

        let round_factor = 10.0 * f64(digits);
        let rounded_float = (full_float * round_factor).round() / round_factor;
        rounded_float
    }

    fn type_name_of<T>(_: T) -> &'static str {
        type_name::<T>()
    }
}

I also tried using the approach where I create a new trait called Float and implement it on f32 and f64 and then pass a generic argument into round_float() that has the Float trait. The problem is that this empty Float trait doesn't have the round() method that's shared by f32 and f64.

The above example demonstrates the need to refactor the methods shared between f32 and f64 into a trait in the standard library so that anyone who wishes to do something specific to float numbers (both f32 and f64) can do so more conveniently by using the Float trait in the generic argument and thereby accessing the methods shared in common between f32 and f64.

@ChayimFriedman2
Copy link

First, never compare the type names of two types. Type names are for debugging purposes only. Compare TypeId instead.

Second, there is already a (well-established) crate that does that. Which might demonstrate that in fact it is not needed to be in the standard library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants