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

Enable Self = F in generic where clause #3610

Closed
amab8901 opened this issue Apr 11, 2024 · 1 comment
Closed

Enable Self = F in generic where clause #3610

amab8901 opened this issue Apr 11, 2024 · 1 comment

Comments

@amab8901
Copy link

Problem

I'm trying to implement a trait method like this:

pub trait RoundToFraction {
    /// Round `float_number` to specified number of digits in the fraction.
    /// # Errors
    /// Throws error if:
    /// * can't instantiate `10.0`
    /// * can't convert `digits` to a Float number
    /// * `digits` is zero
    fn round_to_fraction<F: Float>(&self, digits: u32) -> Result<F>
    where
        Self: Float,
    {
        if digits == 0 {
            return Err(anyhow::Error::msg("`digits` must be a positive integer"));
        }
        let ten = F::from(10.0).ok_or(anyhow::Error::msg("Failed to instantiate value `10.0`."))?;
        let digits =
            F::from(digits).ok_or(anyhow::Error::msg("Failed to convert `digits``to float"))?;
        let round_factor = ten * digits;
        let rounded_float = (self.mul(round_factor)).round() / round_factor;

        Ok(rounded_float)
    }
}

The idea is that Self is a float (f32 or f64), and F is another float. They need to somehow recognize that they are the same type so that they can be multiplied with each other.

Suggested Solution

add the ability to specify that Self = F like this:

    fn round_to_fraction<F: Float>(&self, digits: u32) -> Result<F>
    where
        Self = F,
    {
        [...]

        Ok(rounded_float)
    }
@amab8901 amab8901 changed the title Enable Self = F in generic "where" clause Enable Self = F in generic where clause Apr 11, 2024
@amab8901
Copy link
Author

actually nvm, I found that you can just replace F with Self

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

1 participant