← Back to context

Comment by formerly_proven

2 months ago

Yes, but now you have a slice of MaybeUninit instead of T. This is totally fine for code you control, but out-parameters of the shape &mut [T] are very common for data en/decoding crates, and those require an initialized slice per Rust initialization rules, even if/though most of these will only write to out or reference elements previously written. In practice you can still reserve+set_len, but it is undefined behavior in rust for a &[T] to exist that points to uninitialized memory; at least this is my understanding. If that were not the case, then the spare_capacity_mut API would be kind of pointless?

If something is asking for `&mut [T]`, then yes, it's required that it be initialized. This is a good thing, because a `&mut [T]` permits reading that `T` in safe code, which would be UB if the `T` were uninitialized.

It seems like your complaint is more about "more APIs should accept possibly uninitialized data, but they don't." Which is fair, but I don't know how big of a deal it really is. There is for sure desire to make this work with `std::io::Read`, and indeed, there are unstable APIs for that[1].

[1]: https://doc.rust-lang.org/std/io/trait.Read.html#method.read...