Am 05/12/14 um 14:15 schrieb Nathan Sizemore:
>
> If you're wanting to do comparisons, you will probably want to place a
> trait constraint on your functions from the following
> module: http://doc.rust-lang.org/std/cmp/index.html#traits
>
I tried to write the function (my second Rust code ever). I thought that
returning T makes no sense since the inverse of an integer should be a
float.

Is this the right way?

use std::num;

fn main() {
    fn inverse<T: num::NumCast>(x: T) -> Result<f64, String> {
        let local: f64 = num::cast(x).unwrap();
        if 0f64 == local { return Err("x cannot be zero!".to_string()); }
        Ok(1f64 / local)
    }

    match inverse(5.2f32) {
        Ok(n) => println!("{}", n),
        Err(s) => println!("{}", s)
    }

    match inverse(4i) {
        Ok(n) => println!("{}", n),
        Err(s) => println!("{}", s)
    }
}



_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to