如果我知道有可能,如何将通用T转换为f32? [英] How do I cast generic T to f32 if I know that it's possible?

查看:48
本文介绍了如果我知道有可能,如何将通用T转换为f32?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用的struct,只有一个字段,只能是i32f32.

I have a generic struct with one field, that can only be i32 or f32.

trait MyInt {
    fn blank();
}

impl MyInt for i32 {
    fn blank() {
        unimplemented!()
    }
}

impl MyInt for f32 {
    fn blank() {
        unimplemented!()
    }
}

struct MyStruct<T> where T: MyInt {
    field: T
}

impl<T> MyStruct<T> where T: MyInt {
    fn new(var: T) -> MyStruct<T> {
        MyStruct {
            field: var
        }
    }
}

现在,我想添加一个返回字段值as f32的方法,无论它是i32还是f32.我知道这种转换应该总是可行的,因为字段类型仅限于上述两种类型,但是我该如何处理呢?显然as仅适用于原始类型,并且我尝试采用From路线,但我做错了什么,这是行不通的.

Now I want to add a method which returns field value as f32, whether it's i32 or f32. I know that this cast should always be possible since field types are limited to two mentioned above, but how do I go about it? Apparently as only works on primitive types and I tried going the From route, but I am doing something wrong, this doesn't work.

fn to_f32(&self) -> f32 where T: From<i32> {
        f32::from(self.field);
}

推荐答案

是的,as仅适用于具体类型.

You are right, as only works with concrete types.

使用FromInto特征进行转换是一种很好的方法,但是对于i32-> f32转换,则未实现这些特征.正如Matthieu M.所说,其原因很可能是潜在的转换损失.

Using the From or Into trait for the conversion is a good approach, but these are not implemented for a i32 -> f32 conversion. The reason is most likely that it's a potentially lossy conversion as Matthieu M. says.

您必须使用f64而不是f32.

我建议将特征更改为此:

I would suggest changing the trait to this:

trait MyInt: Copy + Into<f64> {
    fn blank();
}

然后,您可以添加方法进行转换:

Then you can add the method to do the conversion:

fn to_f64(&self) -> f64 {
    self.field.into()
}

这篇关于如果我知道有可能,如何将通用T转换为f32?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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