是否可以根据泛型类型选择常量的值?
例如,类似于(无效的锈蚀代码):
fn foo<T>() {
let b = match T {
u32 => 0x01234567u32,
u64 => 0x0123456789abcdefu64,
_ => panic!()
}
}
fn main() {
foo::<u32>();
foo::<u64>();
}此函数仅用于u16、u32和u64类型的操作。
发布于 2022-06-23 13:48:24
您可以使用一个特征的伴生常数:
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>();
}在生锈操场上试一试。
发布于 2022-06-23 14:05:12
如果您需要做的不仅仅是返回一个值,还可以在泛型的TypeId上匹配,但是您必须将返回值封装在枚举中,因为不能从单个match语句返回多个类型:
use std::any::TypeId;
#[derive(Debug)]
enum Value {
u32(u32),
u64(u64),
}
fn foo<T: 'static>() -> Value {
match TypeId::of::<T>() {
t if t == TypeId::of::<u32>() => {
// other stuff
Value::u32(0x01234567u32)
},
t if t == TypeId::of::<u64>() => {
// other stuff
Value::u64(0x0123456789abcdefu64)
},
_ => panic!(),
}
}
fn main() {
println!("{:?}", foo::<u32>());
println!("{:?}", foo::<u64>());
}但是,如果获得常量值是您需要的唯一功能,那么前面提到的关联常量会更好。
https://stackoverflow.com/questions/72731166
复制相似问题