Hi Peter,

I would do in this way:

use std::fmt::Show;
use std::num::{mod, NumCast};

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

fn dotest<T: NumCast + Show + Clone> (x: T) {
    println!("1/{} => {}", x.clone(), inverse(x));
}

fn main() {
    dotest(5.2f32);
    dotest(4i32);
    dotest(0i);
}

(Disclaimer: it's only three months since I started to learn Rust!)

There is an online compiler, though it's one month old and details of
the language and the stdlib somewhat differ from those of the nightly
version:
http://is.gd/13zBYc (Hit the [evaluate] button)
I think Reddit, StackOverflow and IRC (there's a web interface) are more
active than this list.

Hope this helps.

Kai

野田  開 <[email protected]>

2014-12-05 22:52 GMT+08:00 Péter Mózes Merl <[email protected]>:

>  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
>
>
_______________________________________________
Rust-dev mailing list
[email protected]
https://mail.mozilla.org/listinfo/rust-dev

Reply via email to