11
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();
kmdreko
  • 42,554
  • 6
  • 57
  • 106
Swaroop Maddu
  • 4,289
  • 2
  • 26
  • 38

3 Answers3

10

You can use concat_arrays macro for it:

use concat_arrays::concat_arrays;

fn main() {
    let arr: [u8; 8] = concat_arrays!([97, 112, 112, 108, 101], [0; 3]);
    println!("{:?}", arr);
}

I don't think it's possible to do without external dependencies.

Maxim Gritsenko
  • 2,396
  • 11
  • 25
9

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

Aiden4
  • 2,504
  • 1
  • 7
  • 24
5

You could start with zeros and set the initial values afterwards. This requires arr to be mut though.

fn main() {
    let mut arr: [u8;8] = [0;8];
    let init = [97, 112, 112, 108, 101];
    arr[..init.len()].copy_from_slice(&init);

    println!("Len is {}",arr.len());
    println!("Elements are {:?}",arr);
}

Link to Playground

Rytis I
  • 1,105
  • 8
  • 19