Search code examples
copyrustslicemutability

How to easily copy a non-mut &[u8] into to a &mut [u8]


I want to do some manipulations on a &mut [u8].

In my testing code I have:

#[test]
fn test_swap_bytes() {
    let input: &[u8] = b"abcdef";
    let result: &mut[u8] = ?;
    do_something(result);
    assert_eq!(b"fedcba", result);
}

How can I easily get a mutable u8 slice in this case? What should I put on the place of the question mark?


Solution

  • You can use the fact that a binary literal knows its size at compile-time. Therefor you can dereference it and store it on the stack. Any let binding can also be a mutable let binding.

    let mut input: [u8; 6] = *b"abcdef";
    

    See PlayPen for a fully working example

    Note that there's no reason to specify the type, I just showed it for clarity.