簡體   English   中英

只接受Rust Generic中的原始類型

[英]Only accept primitive types in a Rust Generic

有沒有辦法讓Rust Generic只接受原始類型? 我想稍后迭代值中的位,我明白這只能用於原始類型。

struct MyStruct<T> {
    my_property: T // my_property HAS to be a primitive type
}

我相信你能得到的最接近的東西是為內置數字類型實現的Primitive特征。 它是幾個其他數字特征的組合,最終允許對這些值進行比特擺弄。 您可能還需要添加BitAnd / BitOr / BitOr traits,因為Primitive似乎不允許這些操作:

fn iter_bits<T: Primitive+BitAnd<T, T>+BitOr<T, T>>(x: T) { /* whatever */ }

由於您似乎有自定義要求,因此您可以使用具有所需特定功能的自定義特征,例如

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 { ... }

(無論如何,這是“迭代比特”的一種解釋。)

然后,使用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