Why does a destination for copy_from_slice need to be initialised?

Hi,

Please consider the example code in the Rust documentation for copy_from_slice:

It occurs to me that this u8 is initialised as all zeroes and then immediately overwritten. I've noted that if you change the declaration to:

let mut dst: [u8; 2];

You'll get a compile error for

`dst` used here but it isn't initialized

I'm just a bit confused about how you're "using" that value at all if all you're doing is immediately attempting to copy data over the top of it (which is what I would like to call "initialising") without looking at it. Which I guess noone cares about for this example, but I'm currently writing some code with a number of larger buffers and the workflow just seems off.

Because having a reference to uninitialized data is UB, and that method takes an exclusive reference. (Also consider if you tried that on an uninitialized [String; 2]. You'd try to deallocate garbage when you overwrote the uninitialized values.)

The compiler is usually smart enough to optimize that initialization away. For cases where you're sure it's not, see MaybeUninit.

2 Likes

Note that even if it weren't UB to have a reference to uninitialized data, this wouldn't compile.

Mutable references can be read from (they are not write-only), so the compiler couldn't just assume based on the signature that the function only writes to dst and doesn't read from it.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.