我正在实现一个 Bit Vector 类作为练习,但是只知道 Rust 不到一周,我遇到了以下代码的麻烦:
use std::cmp::Eq;
use std::ops::BitAnd;
use std::ops::Index;
use std::ops::Not;
struct BitVector<S = usize>
where S: Sized + BitAnd<usize> + Not + Eq {
data: Vec<S>,
capacity: usize
}
impl<S> BitVector<S>
where S: Sized + BitAnd<usize> + Not + Eq {
fn with_capacity(capacity: usize) -> BitVector {
let len = (capacity / (std::mem::size_of::<S>() * 8)) + 1;
BitVector { data: vec![0; len], capacity: capacity }
}
}
impl<S> Index<usize> for BitVector<S>
where S: Sized + BitAnd<usize> + Not + Eq {
type Output = bool;
fn index(&self, index: usize) -> &bool {
let data_index = index / (std::mem::size_of::<S>() * 8);
let remainder = index % (std::mem::size_of::<S>() * 8);
(self.data[data_index] & (1 << remainder)) != 0
}
}
这个想法S可以是例如u8, u16, , 之一u32,u64并usize确保将其设置为0in创建一个由全零组成的with_capacity位值。S
我得到的错误如下:
lib.rs:27:10: 27:50 错误:二进制操作
!=不能应用于类型<S as std::ops::BitAnd<usize>>::Output[E0369]
lib.rs:27 (self.data[data_index] & (1 << remaining)) != 0
^~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
lib.rs:27:10:27:50 帮助:运行rustc --explain E0369查看详细说明
lib.rs:27:10: 27:50 注意:lib.rs: 27 (self.data[std::cmp::PartialEqdata_index<S as std::ops::BitAnd<usize>>::Output
] & (1 << remaining)) != 0 ^~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
错误:由于先前的错误而中止
错误:无法编译bit-vector.