如何在Rust中转换泛型基本类型? [英] How to convert generic primitive types in Rust?

查看:86
本文介绍了如何在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

查看 / a>,我了解到 From 特性不适用于 i32 f32 转换,这是我最初想要的。

Looking at How do I cast generic T to f32 if I know that it's possible?, I learnt that the From trait doesn't work for i32 to f32 conversion, which is what I wanted originally.

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

The simplest solution I can come up with is to write a function like:

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

Clearly Rust从 i32 转换为 f32 毫无问题。

Clearly Rust has no problem casting from i32 to f32. Is there a nicer way to write this?

推荐答案

您可以使用来自特征rel = nofollow noreferrer > num

示例(您可以避免使用AsPrimitive选项):

you can use ToPrimitive trait from num
example (you can avoid Option with 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);
}

这篇关于如何在Rust中转换泛型基本类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆