Home > other >  Idiomatic way in Rust to dump slice contents onto an array?
Idiomatic way in Rust to dump slice contents onto an array?

Time:10-13

I was doing something like this:

type HashId = [u8; 32];

fn fill_hash_id(hash_id: &mut HashId, hash_data: &[u8]) {
    for i in 0..32 {
        hash_id[i] = hash_data[i];
    }
    ()
}

Is there a better, more direct or idiomatic way for this in Rust?

CodePudding user response:

To expand a comment on your question into a full answer:

The slice method copy_from_slice will work.

Because an an array [T; N] implements AsMut<[T]>* (that is, a reference to a mutable array of T can be treated as a mutable slice of T), you can call this method on an array.

type HashId = [u8; 32];

fn main() {
    let mut hash_id: HashId = [0u8; 32];
    let hash_data = vec![1u8; 32];
    
    hash_id.copy_from_slice(&hash_data);
    
    println!("{:?}", &hash_id);
    // bunch of '1's
}

But be careful; copy_from_slice will panic if the target and receiver aren't the same length.

*Full disclosure: [T; N] also implements BorrowMut<T>, and while I'm pretty sure AsMut is the trait that's in play here, I'm not 100% sure it's not BorrowMut.

  • Related