generics - 根据rust函数中的泛型选择常量

标签 generics rust

有没有办法根据泛型类型选择常量的值?

例如,类似(无效的 Rust 代码):

fn foo<T>() {
    let b = match T {
        u32 => 0x01234567u32,
        u64 => 0x0123456789abcdefu64,
        _ => panic!()
    }
}

fn main() {
    foo::<u32>();
    foo::<u64>();
}

此函数仅设计为与 u16u32u64 类型一起使用。

最佳答案

你可以使用一个特征的associated constant:

trait MyTrait {
    const SOME_CONST: Self;
}

impl MyTrait for u32 {
    const SOME_CONST: Self = 0x01234567u32;
}

impl MyTrait for u64 {
    const SOME_CONST: Self = 0x0123456789abcdefu64;
}

fn foo<T>() where T: MyTrait {
    let _b: T = T::SOME_CONST;
}

fn main() {
    foo::<u32>();
    foo::<u64>();
}

rust playground 上试试。

关于generics - 根据rust函数中的泛型选择常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72731166/

相关文章:

c# - 如何编写指定创建逻辑的接口(interface)或抽象类?

generics - Rust 泛型 : Expected <T> found <Foo>

rust - Rust按位运算

rust - 如何在 Rust 中实现异步 Drop?

rust - 为什么 "one type is more general than the other"在包含闭包的选项中?

java - ArrayList 包含错误的类型对象,没有明确的原始类型转换

c# - Hashset 与 IQueryable

java - 不兼容的类型,但没有意义(Java)

java - 为什么 Java Collections 的移除方法不是通用的?

rust - 向向量添加临时值时的生命周期