如何在rust中转换通用原始类型?

时间:2019-04-26 12:11:48

标签: generics casting rust

我想在rust中编写如下内容:

pub struct Point<T> {
    pub x: T,
    pub y: T,
}

impl<T> Point<T> {
    pub fn from<U>(other: Point<U>) -> Point<T> {
        Point {
            x: other.x as T,
            y: other as T,
        }
    }
}

这是不可能的:

error[E0605]: non-primitive cast: `U` as `T`
 --> src/lib.rs:9:16
  |
9 |             x: other.x as T,
  |                ^^^^^^^^^^^^
  |
  = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

通过查看此answer,我了解到From特性对于i32f32的转换不起作用,这是我最初想要的。

我能想到的最简单的解决方案是简单地编写一个像这样的函数:

pub fn float2_from_int2(v: Point<i32>) -> Point<f32> {
   Point::<f32>::new(v.x as f32, v.y as f32)
}

i32f32的锈迹很明显。有没有更好的方法来写这个?

1 个答案:

答案 0 :(得分:2)

您可以使用ToPrimitive中的num特征
示例(可以避免使用AsPrimitive选项):

pub struct Point<T> {
    pub x: T,
    pub y: T,
}

impl<T: Copy + 'static> Point<T> {
    pub fn from<U: num::cast::AsPrimitive<T>>(other: Point<U>) -> Point<T> {
        Point {
            x: other.x.as_(),
            y: other.y.as_(),
        }
    }
}

fn do_stuff() {
    let a = Point{x: 0i32, y: 0i32};
    let b = Point::<f32>::from(a);
}