问题描述
我是Rust的初学者。我正在尝试使用BitVec库表示位数组。我通过添加0或1的序列开始玩游戏,但是这样做有些麻烦。当我附加一个x 0s的序列 then 一个y 1s的序列时,它要做的是附加x + y零。请注意,如果我只是追加1而没有追加0,那么它会起作用。这是我的代码:
extern crate bit_vec;
use bit_vec::BitVec;
fn main(){
let mut bits = BitVec::new(); // creates an empty array of bits
append_zero(&mut bits);
append_one(&mut bits);
append_zero(&mut bits);
append_one(&mut bits);
append_one(&mut bits); // everything works perfectly till here
append_n_ones(&mut bits,2); // this works
append_n_zeroes(&mut bits,3); // this too
append_n_ones(&mut bits,2); // this appends 2 zeroes instead!
println!("{:?}",bits);
}
fn append_zero(vector: &mut BitVec) {
vector.push(false);
}
fn append_one(vector: &mut BitVec) {
vector.push(true);
}
fn append_n_zeroes(vector: &mut BitVec,n: usize) {
let mut to_append = BitVec::from_elem(n,false); // creates a BitVec with n 0s
println!("trying to append: {:?}",to_append);
vector.append(&mut to_append);
}
fn append_n_ones(vector: &mut BitVec,true); // creates a BitVec with n 1s
println!("trying to append: {:?}",to_append);
vector.append(&mut to_append);
}
这是输出:
trying to append: 11
trying to append: 000
trying to append: 11
010111100000
请注意,最后一行应该是010111100011
。此外,在附加之前,11
已正确打印。但随后会附加00
。
我正在使用this website测试我的Rust代码,但是在本地它有相同的问题。我尝试查看code for the BitVec library,但对于目前的Rust水平而言,它太高级了。
解决方法
bit_vec
的板条箱虽然古老而又很流行,但仅用于维护。我是替代产品bitvec
的作者,该产品的行为符合您的期望,并且(我认为)是更好的产品。
您可以通过将bit_vec
替换为{{1},将bitvec
替换为BitVec::from_elem
来使用编写的代码。不幸的是,BitVec::<Lsb0,usize>::repeat
在Rust游乐场上不可用,因此我无法直接向您显示。