Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

rust - Is there any way to restrict a generic type to one of several types?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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> { ... }

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...