generics - 如何在 Rust 中转换泛型原始类型?

标签 generics casting 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

查看How do I cast generic T to f32 if I know that it's possible? ,我了解到 From 特性不适用于 i32f32 的转换,这正是我最初想要的。

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

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

很明显,Rust 从 i32 转换为 f32 没有问题。有更好的写法吗?

最佳答案

你可以使用ToPrimitive来自 num 的特征
示例(您可以使用 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);
}

关于generics - 如何在 Rust 中转换泛型原始类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867367/

相关文章:

Java 8 Predicate - 为什么不能连接通配符泛型谓词?

rust - 如何使用数学方法围绕 ggez 图像的中心而不是左上角旋转?

rust - 我如何强制执行父子结构生命周期?

java - 为什么我不能使用带有通配符的多个类型参数?

C++ 比较指向不同类型的指针?

java - 非泛型类中的 Java 泛型问题

java - 如何避免许多小类的代码重复?

arrays - 如何将 byte slice 段 (&[u8]) 的缓冲区转换为整数?

java - long mod 操作返回 int Java

rust - 除了关键字之外,Rust 是否有任何保留的标识符(例如以下划线开头)?