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?
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.
Correct Option: C. Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw 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 .
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.
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 impl
s to encapsulate the logic specific to u16
, u32
and u64
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With