首页 > 解决方案 > 如何在 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

查看如果我知道有可能,如何将通用 T 转换为 f32?,我了解到该From特征不适用于i32转换f32,这是我最初想要的。

我能想到的最简单的解决方案是编写如下函数:

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

i32显然,Rust 从to转换没有问题f32。有没有更好的方法来写这个?

标签: genericscastingrust

解决方案


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

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);
}

推荐阅读