Is there a way I can have a Rust Generic only accept primitive types? I want to later iterate over the bits in the value, and I understand that that's only possible with primitive types.
struct MyStruct<T> {
my_property: T // my_property HAS to be a primitive type
}
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
Rust can make use of generics in several places: Function Definitions. Struct Definitions. Enum Definitions.
You can substitute a generic type with a primitive data type.
The Rust language has a number of types that are considered 'primitive'. This means that they're built-in to the language. Rust is structured in such a way that the standard library also provides a number of useful types built on top of these ones, as well, but these are the most primitive.
I believe the closest thing you can get is Primitive
trait which is implemented for in-built numeric types. It is a combination of several other numerical traits, which, in the end, allows for bit-fiddling with the values. You will also probably need to add BitAnd
/BitOr
/etc. traits, because Primitive
only does not seem to allow these operations:
fn iter_bits<T: Primitive+BitAnd<T, T>+BitOr<T, T>>(x: T) { /* whatever */ }
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