简体   繁体   中英

Rust iterate over ChunkExactMut -> use of moved value

i am a C++ Developer and try to learn Rust. I got a use of moved value error. I think it is because the ChunkExactMut iterator has no copy implemented. But the step_by function should create a new iterator (Rust documentation).

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.

What is the rust way to write it? Or a good way. I thought usage of iterators would be a more safe approach than a pointer or vec[index] = value implementation.

/// 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
}

Currently i use this, but iam just currious if there are more better options in 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM