Search code examples
rustrust-macros

How to pad an array with zeros?


fn main() {
    let arr: [u8;8] = [97, 112, 112, 108, 101];
    println!("Len is {}",arr.len());
    println!("Elements are {:?}",arr);
}
error[E0308]: mismatched types
 --> src/main.rs:2:23
  |
2 |     let arr: [u8;8] = [97, 112, 112, 108, 101];
  |              ------   ^^^^^^^^^^^^^^^^^^^^^^^^ expected an array with a fixed size of 8 elements, found one with 5 elements
  |              |
  |              expected due to this

Is there any way to pad the remaining elements with 0's? Something like:

let arr: [u8;8] = [97, 112, 112, 108, 101].something();

Solution

  • In addition to the other answers, you can use const generics to write a dedicated method.

    fn pad_zeroes<const A: usize, const B: usize>(arr: [u8; A]) -> [u8; B] {
        assert!(B >= A); //just for a nicer error message, adding #[track_caller] to the function may also be desirable
        let mut b = [0; B];
        b[..A].copy_from_slice(&arr);
        b
    }
    

    Playground