Limit a generic type to one of several types

I am trying to create a generic structure that uses an "integer type" to reference an array. For performance reasons, I would like to easily indicate whether to use u16, u32or u64. Something like this (which is clearly not valid Rust code):

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

Is there any way to express this?

+4
source share
1 answer

For array references, you usually just use usizedifferent integer types instead.

However, in order to do what you need, you can create a new trait, implement this trait for u16, u32and u64then restrict T to a new property.

pub trait MyNewTrait {}

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

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

MyNewTrait impl, , u16, u32 u64.

+7

Source: https://habr.com/ru/post/1661768/


All Articles