有没有办法将泛型类型限制为几种类型之一? [英] Is there any way to restrict a generic type to one of several types?

查看:34
本文介绍了有没有办法将泛型类型限制为几种类型之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用结构,它使用整数类型"来引用数组.出于性能原因,我希望能够轻松指定是使用 u16u32 还是 u64.像这样的东西(这显然不是有效的 Rust 代码):

I'm trying to create a generic struct which uses an "integer type" for references into an array. For performance reasons I'd like to be able to specify easily whether to use u16, u32 or u64. Something like this (which obviously isn't valid Rust code):

struct Foo<T: u16 or u32 or u64> { ... }

有什么方法可以表达吗?

Is there any way to express this?

推荐答案

对于数组的引用,通常你只需要使用 usize 而不是不同的整数类型.

For references into an array usually you'd just use a usize rather than different integer types.

但是,要在创建新特征后执行您的操作,请为 u16u32u64 实现该特征,然后将 T 限制为您的新特征.

However, to do what you are after you can create a new trait, implement that trait for u16, u32 and u64 and then restrict T to your new trait.

pub trait MyNewTrait {}

impl MyNewTrait for u16 {}
impl MyNewTrait for u32 {}
impl MyNewTrait for u64 {}

struct Foo<T: MyNewTrait> { ... }

然后您还可以在 MyNewTraitimpl 上添加方法来封装特定于 u16u32u64.

You may then also add methods onto MyNewTrait and the impls to encapsulate the logic specific to u16, u32 and u64.

这篇关于有没有办法将泛型类型限制为几种类型之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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