Skip to content

Guide: Fixing Inverse in Generics section #17224

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

Closed
prakhar1989 opened this issue Sep 13, 2014 · 3 comments · Fixed by #21109
Closed

Guide: Fixing Inverse in Generics section #17224

prakhar1989 opened this issue Sep 13, 2014 · 3 comments · Fixed by #21109

Comments

@prakhar1989
Copy link

In the section on Generics, the inverse function is introduced which gives inverse of a f32 and f64. The section uses this following code to demonstrate the usage of Traits but then doesn't provide an example of how to fix the original problem.

fn inverse<T>(x: T) -> Result<T, String> {
    if x == 0.0 { return Err("x cannot be zero!".to_string()); }

    Ok(1.0 / x)
}

As a beginner, I found it a bit hard to make this work as the solution is quite unintuitive for someone new to rust.

fn inverse<T: Float>(x: T) -> Result<T, String> {
    // converting slice to String
    let f0: T = std::num::Zero::zero();
    let f1: T = std::num::One::one();
    if x == f0 { return Err("x cannot be zero!".to_string()); }
    Ok(f1 / x)
}

It would be great if after the diversion to Traits the generics section closes off with a solution to the inverse problem with a bit of explanation of std::num module.

@huonw huonw added the A-docs label Sep 13, 2014
@huonw
Copy link
Member

huonw commented Sep 13, 2014

cc @steveklabnik

(BTW, your replacement code can use std::num::one and call .is_zero, i.e.

fn inverse<T: Float>(x: T) -> Result<T, &'static str> {
    if x.is_zero() { return Err("x cannot be zero!") }

    Ok(std::num::one::<T>() / x)
}

Not super important of course.)

@prakhar1989
Copy link
Author

Thanks @huonw 👍

@steveklabnik
Copy link
Member

Is this still the way to go with the changes to std::num?

steveklabnik added a commit to steveklabnik/rust that referenced this issue Jan 13, 2015
alexcrichton added a commit to alexcrichton/rust that referenced this issue Jan 15, 2015
lnicola pushed a commit to lnicola/rust that referenced this issue May 19, 2024
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

Successfully merging a pull request may close this issue.

3 participants