简体   繁体   中英

Only accept primitive types in a Rust Generic

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
}

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 */ }

Since you seem to have custom requirements, you could use a custom trait with the specific functionality you need, eg

trait BitIterate {
    /// Calls `f` on each bit of `self`, passing the index and the value.
    fn each_bit(&self, f: |uint, bool|);
}


impl BitIterate for u8 { ... }
impl BitIterate for u16 { ... }
// etc... could be done with a macro

// a non-primitive type which has a sensible way to iterate over bits
impl BitIterate for std::collections::Bitv { ... }

(That's one interpretation of "iterate over bits" anyway.)

Then, functions using MyStruct and needing iterable bits would use something like

fn print_bits<T: BitIterate>(x: MyStruct<T>) {
    x.my_property.each_bit(|index, bit_value| {
        println!("bit #{} is {}", index, bit_value);
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM