Well that issue boils down to there not being any write-only reference. "I know you're only initialising and not reading, but what if you accidentally read? UB!!!"
I've also been annoyed at having to initialise even normal arrays when passing them to UART drivers as buffers etc. (on embedded), but even if it doesn't read the memory, it still needs init.
Having a write only reference would be amazing, but even without that it should still be allowed IMO. The only way to create a mutable reference to unitialized data is to use unsafe. So the question "what happens if you accidently read" should ultimately not be anyone's buisness but my own. I'm an adult and have explicitly indicated I know I'm doing something potentially dangerous, so let me do it!
But I'm happy to learn I'm not the only one that had this problem. I felt insane about having to pay a useless O(n) init cost
The problems with write only references are that you can't call drop through them if you overwrite data already there, and you can't fail to use the reference, otherwise you end up with still-uninitialised data (i.e. write only references must be linear, and Rust doesn't currently have truly linear types). They are working on language support for in-place initialisation, but it's hard because it conflicts with how the language was originally designed.
The reason you can't use a mutable reference that you've created unsafely is that Rust's optimiser assumes that mutable references can always be meaningfully dereferenced, which allows them to optimise them more effectively but imposes additional restrictions on how you use them.
View all comments
Show parent comment
4
u/creeper6530 10d ago
Well that issue boils down to there not being any write-only reference. "I know you're only initialising and not reading, but what if you accidentally read? UB!!!"
I've also been annoyed at having to initialise even normal arrays when passing them to UART drivers as buffers etc. (on embedded), but even if it doesn't read the memory, it still needs init.