Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 仅接受Rust泛型中的基元类型_Generics_Rust - Fatal编程技术网

Generics 仅接受Rust泛型中的基元类型

Generics 仅接受Rust泛型中的基元类型,generics,rust,Generics,Rust,有没有办法让Rust泛型只接受基元类型?我想稍后对值中的位进行迭代,我知道这只适用于基本类型 struct MyStruct<T> { my_property: T // my_property HAS to be a primitive type } struct MyStruct{ my_属性:T//my_属性必须是基元类型 } 我相信你能得到的最接近的东西是trait,它是为内置数字类型实现的。它是其他几个数字特征的组合,最终允许对数值进行微调。您可能还需要添加位和/

有没有办法让Rust泛型只接受基元类型?我想稍后对值中的位进行迭代,我知道这只适用于基本类型

struct MyStruct<T> {
    my_property: T // my_property HAS to be a primitive type
}
struct MyStruct{
my_属性:T//my_属性必须是基元类型
}

我相信你能得到的最接近的东西是trait,它是为内置数字类型实现的。它是其他几个数字特征的组合,最终允许对数值进行微调。您可能还需要添加
位和
/
位或
/等特征,因为
原语
似乎只允许以下操作:

fn iter_bits<T: Primitive+BitAnd<T, T>+BitOr<T, T>>(x: T) { /* whatever */ }
fn iter_位(x:T){/*无论什么*/}

既然您似乎有定制需求,您可以将定制特性与所需的特定功能结合使用,例如:

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);
    })
}
fn打印位(x:MyStruct){
x、 my_属性。每个_位(|索引,位_值|){
println!(“位{}是{}”,索引,位值);
})
}

你到底想在比特上迭代什么?“基本类型”在Rust中不是一个有意义的概念。有这样的类型,但这是在这方面最接近的,它允许以模块化的方式传输布尔值。我可以将它预先设置为byte、short、int等,但这不允许as模块化设计。我仍然不理解。“以模块化方式传输布尔值”是什么意思?我认为您可能试图以次优的方式执行某些操作,但有更好的方法。@ChrisMorgan将其视为不使用堆的位图。看起来,基本特征在2014年7月后的某个时候被删除,因此此解决方案不再像这样工作,需要多行。有关更新,请参阅。