How can I create an is_prime function that is generic over various integer types?

后端 未结 2 1018
耶瑟儿~
耶瑟儿~ 2020-12-09 07:56

I just took the dive into Rust and want to make some basic math functions that are generic. I have the following is_prime function:

fn is_prime(         


        
2条回答
  •  醉梦人生
    2020-12-09 08:28

    To add to Chris Morgan's answer, you can use num::NumCast::from to cast to a generic number type where using Zero and One would be inappropriate. In your case:

    use num::{Num, NumCast};
    
    fn is_prime(n: N) -> bool {
        let _0: N = NumCast::from(0usize).unwrap();
        let _1: N = NumCast::from(1usize).unwrap();
        let _2: N = NumCast::from(2usize).unwrap();
        let _3: N = NumCast::from(3usize).unwrap();
        let _4: N = NumCast::from(4usize).unwrap();
        let _5: N = NumCast::from(5usize).unwrap();
        let _6: N = NumCast::from(6usize).unwrap();
    

提交回复
热议问题