Swaroop Maddu
Swaroop Maddu

Reputation: 4854

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();

Upvotes: 11

Views: 7494

Answers (3)

Aiden4
Aiden4

Reputation: 2654

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

Upvotes: 10

Rytis I
Rytis I

Reputation: 1303

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

Upvotes: 5

Maxim Gritsenko
Maxim Gritsenko

Reputation: 2592

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.

Upvotes: 10

Related Questions