Is there a trait for scalar-castable types?

与世无争的帅哥 提交于 2019-12-10 16:27:17

问题


I'm stuck with this code for operator overloading.

use std::ops::Add;

struct Test<T: Add>{
    m:T
}

impl<T:Add> Add for Test<T>{
    type Output = Test<T>;
    fn add(self, rhs: Test<T>) -> Test<T> {
        Test { m: (self.m + rhs.m) as T }
    }
}

I cannot cast (self.m + rhs.m) to T because it is a non-scalar cast.

Is there a trait for types scalar-castable to T?


回答1:


No, there isn't a trait covering this functionality. Only some casts are possible and their full list can be found in The Book.

As for your Add implementation, you should modify it in the following manner in order for it to work:

use std::ops::Add;

struct Test<T: Add>{
    m: T
}

impl<T> Add for Test<T> where T: Add<Output = T> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Test { m: self.m + rhs.m }
    }
}

You can find a good explanation why the additional T: Add<Output = T> bound is necessary in this SO answer. This one might be even closer to your exact case.



来源:https://stackoverflow.com/questions/41869048/is-there-a-trait-for-scalar-castable-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!