【问题标题】:How to convert specific type to generic type (all built-in type)?如何将特定类型转换为泛型类型(所有内置类型)?
【发布时间】:2021-07-14 06:36:46
【问题描述】:

我想将特定类型返回泛型类型,都是内置类型,所以不能impl From for u32 { ... }

fn fn1<T>() -> T {
    let a = 123u64;
    a as T
    // ^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
}

fn main() {
    let a = fn1::<u32>();
    dbg!(a);
}

有什么好的方法吗?

【问题讨论】:

  • 这看起来像XY question。对于您的实际问题,可能有一个明智的解决方案。这是什么?

标签: generics types rust


【解决方案1】:

首先,您应该注意,您所做的事情从根本上来说是不安全的,因为您要在较小的类型中安装较大的类型。

然后,您应该使用特征来指定您的泛型函数适用于可以被转换的类型:

use std::convert::{TryFrom, TryInto};

fn fn1<T: TryFrom<u64>>() -> T {
    let a = 123u64;
    a.try_into().unwrap_or_else(|_| {
        panic!("maybe improve the behavior here");
    })
}

fn main() {
    let a = fn1::<u32>();
    dbg!(a);
}

【讨论】:

  • TryFrom 不受孤儿规则约束?
  • @Anunaki 我不理解你对这个评论的意思。你没有实现这个特征,只是使用它。如果需要,您可以在自己的类型上实现它。
【解决方案2】:

我找到了办法,但我不确定是否存在大问题:


fn fn1<T: Default + Copy>() -> T {
    let mut a = 123456789u64;
    let t = unsafe { std::mem::transmute::<&mut u64, &mut T>(&mut a) };
    *t
}

fn main() {
    let a = fn1::<u32>();
    dbg!(a);
}

【讨论】:

  • 对任何类型执行此操作都是非常不安全的。您正在绕过类型系统并对任何类型的内部存储做出不合理的假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
相关资源
最近更新 更多