Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only accept primitive types in a Rust Generic

Tags:

generics

rust

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
}
like image 929
Jeroen Avatar asked Jul 10 '14 14:07

Jeroen


People also ask

Can primitive types be used in generics?

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.

Does Rust support generic types?

Rust can make use of generics in several places: Function Definitions. Struct Definitions. Enum Definitions.

Can you substitute a generic type with a primitive data type?

You can substitute a generic type with a primitive data type.

What are primitives in Rust?

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.


1 Answers

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 */ }
like image 57
Vladimir Matveev Avatar answered Oct 21 '22 04:10

Vladimir Matveev