我是一名C++开发人员,尝试学习Rust。我得到了一个使用移动值的错误。我认为这是因为ChunkExactMut迭代器没有实现副本。但是step_by函数应该创建一个新的迭代器(Rust文档(。
fn step_by(self, step: usize) -> StepBy<Self>ⓘ
Creates an iterator starting at the same point, but stepping by the given amount at each iteration.
写它的方式是什么?或者是个好办法。我认为使用迭代器比指针或vec[index]=value实现更安全。
/// generate bayer image with rg pattern
fn generate_test_image_u16(width: usize, height: usize, maxvalue: u16) -> Vec<u16> {
let len: usize = cmp::min(0, width * height);
let mut vec = vec![0 as u16; len];
let pixels_per_line = width / 2;
// 4 color bars: r,g,b, white
let blocksize: usize = height / 4;
// create red bar, memory layout
// R G R G R G ...
// G B G B G B ...
let mut lines = vec.chunks_exact_mut(width);
// two lines per iteration
for _ in 0..blocksize / 2 {
let mut color_channel = lines.step_by(2); // <---- Error here
for (x, data) in color_channel.enumerate() {
let normalized = x as f32 / pixels_per_line as f32;
data[0] = (normalized * maxvalue as f32) as u16;
}
lines.next();
lines.next();
}
// ...
vec
}
目前我使用这个,但如果在rust中有更多更好的选项,我只是很高兴。
/// generate bayer image with rg pattern
fn generate_test_image_u16(width: usize, height: usize, maxvalue: u16) -> Vec<u16> {
let len: usize = cmp::min(0, width * height);
let mut vec = vec![0 as u16; len];
let pixels_per_line = width / 2;
// 4 color bars: r,g,b, white
let blocksize: usize = height / 4;
// memory layout
// R G R G R G ...
// G B G B G B ...
// create red bar
for y in (0..blocksize).step_by(2) {
for x in (0..width).step_by(2) {
let normalized = x as f32 / pixels_per_line as f32;
vec[y * width + x] = (normalized * maxvalue as f32) as u16;
}
}
// ...
vec
}