Create an array with the same length

I am writing something that writes images with lodepng rust and I would like to work with pixels instead of u8

s. I created a structure

struct Pixel {r: u8, g: u8, b: u8}

      

and create an array from array u8

elements. Since I am making the array by hand now, in a strange situation I need to make another array manually. Is there a way to create an array that is three times the length of the pixel array at compile time? Something like

let data: [u8, ..other_array.len()*3];

      

This doesn't work because it is .len()

not compile-time constant. In this case, the execution cost doesn't matter to me, but if I had associated dimensions it would be cleaner (and I might need performance in the future).

Edit: The solution I'm using is based on Levance's answer. For people not manually initializing your array, just follow Levans. I initialize my first array manually, but set the type to use the length given in pixel_count

so that it doesn't get caught pixel_count

in the compile-time trap . I create a second array with this constant and then assert that the lengths have the correct ratio. My minimal example looks like this:

struct Pixel {r: u8, g: u8, b: u8}
static pixel_count : uint = 4;

fn main() {
    let pixel_data = [Pixel, ..pixel_count] = [
                      Pixel {r: 255, g: 0, b: 0},
                      Pixel {r: 0, g: 255, b: 0},
                      Pixel {r: 0, g: 0, b: 255},
                      Pixel {r: 0, g: 99, b: 99}
                     ];
    let mut data = [0u8, ..pixel_count*3];
    assert!(pixel_data.len()*3 == data.len());
}

      

+3


source to share


1 answer


The easiest way to create size-related arrays is to keep the original size as an element const

: they are compile-time constants:



const pixel_count: uint = 42;

struct Pixel { r: u8, g: u8, b: u8 }

fn main() {
    let pixels = [Pixel { r: 0, g: 0, b: 0 }, ..pixel_count];
    let raw_data = [0u8, ..pixel_count * 3];
    assert!(pixels.len() * 3 == raw_data.len());
}

      

+3


source







All Articles