简体   繁体   English

只接受Rust Generic中的原始类型

[英]Only accept primitive types in a Rust Generic

Is there a way I can have a Rust Generic only accept primitive types? 有没有办法让Rust Generic只接受原始类型? 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. 我相信你能得到的最接近的东西是为内置数字类型实现的Primitive特征。 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. 您可能还需要添加BitAnd / BitOr / BitOr traits, because Primitive only does not seem to allow these operations: traits,因为Primitive似乎不允许这些操作:

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 然后,使用MyStruct并需要可迭代位的函数将使用类似的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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