Dividing a const by a generic in Rust

前端 未结 1 1182
梦毁少年i
梦毁少年i 2021-01-05 09:04

I have a struct Vec3, how can I implement the following method ?

impl Not> for Vec3         


        
相关标签:
1条回答
  • 2021-01-05 09:35

    Literals can only be of primitive types. You can't cast a literal to some generic type.

    For constants like 1.0 you can use methods like Float::one(), so your specific example could be rewritten as

    impl<T: num::Float> Not<Vec3<T>> for Vec3<T> {
        fn not(&self) -> Vec3<T> {
            *self * (num::Float::one() / (*self % *self).sqrt())
        }
    }
    

    (note that I removed Num bound because it is deprecated and in this case it is entirely superseded by Float)

    To convert arbitrary values to instances of some specific Float type you can use NumCast::from() method:

    let x: T = num::NumCast::from(3.14f64);
    

    BTW, you may find this accepted RFC interesting.

    Update

    It is likely that you won't be able to implement Float for your structure because it has a lot of methods specific to bare floats, like mantissa size. I guess you will have to add methods like one() and zero() and probably casts from numbers yourself. Then you will be able to write

    impl<T: num::Float> Not<Vec3<T>> for Vec3<T> {
        fn not(&self) -> Vec3<T> {
            *self * (Vec3::one() / (*self % *self).sqrt())
        }
    }
    
    0 讨论(0)
提交回复
热议问题