Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 240
Henning Koehler Avatar asked Nov 23 '16 23:11

Henning Koehler


People also ask

How do I restrict a generic type in Java?

Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

What Cannot be Parameterized with a type using generics?

Correct Option: C. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type.

What can not be a generic type?

Almost all reference types can be generic. This includes classes, interfaces, nested (static) classes, nested interfaces, inner (non-static) classes, and local classes. The following types cannot be generic: Anonymous inner classes .

Are there any situations where generic type information is available at runtime?

It's important to realize that generic type information is only available to the compiler, not the JVM. In other words, type erasure means that generic type information is not available to the JVM at runtime, only compile time.


1 Answers

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.

like image 190
Lukazoid Avatar answered Sep 20 '22 00:09

Lukazoid