How do you copy between arrays of different sizes in Rust?

Manually one can do

for (dst, src) in array1.iter_mut().zip(&array2) {
    *dst = *src
}

for a typical slice. However, there is a likely faster specialization in clone_from_slice:

dst[..4].clone_from_slice(&src)

A slightly older method is to use std::io::Write, which was implemented for &mut [u8].

use std::io::Write;
let _ = dst.write(&src)

This will write up to the end of dst and return how many values were written in a Result. If you use write_all, this will return an Err if not all bytes could be written.

Leave a Comment