3 ms·
> There is a way to have your cake and eat it too: rust. Suppose my cake is that I have a struct A which holds a value, that doesn't have a default value, from
by delusional 2y ago
> There is a way to have your cake and eat it too: rust.
Suppose my cake is that I have a struct A which holds a value, that doesn't have a default value, from your library B. Suppose that at the time I want to allocate A I don't yet have the information I need to initialize B, but I also know that I won't need B before I do have that information and can initialize it. In simple terms. I want to allocate A, which requires allocating B, but I don't want to initialize B, yet.
What do I do?
If you answer involves Option<B> then you're asking me to to grow my struct for no gain. That is clearly not _better_.
- the_gipsy 2y agoThen you can't eat it too (or else you'll get very sick with NPEs/panics), sorry.
- whytevuhuni 2y agoMore specifically, it could result in undefined behavior, if a panic happens between the allocation and initialization (i.e., it was allocated, not initialized, panicked, and something observed the incomplete struct after the panic). Alternatively, the allocation would always have to leak on panic, or the struct would have to be deallocated without a destructor running.
- tsimionescu 2y agoDoesn't Rust have explicit support for uninitialized memory, using the borrow checker to make sure you don't access it before initializing it? Or does that just work for local variables, not members of structs?
- steveklabnik 2y agoYou can’t do the “declare before initializing” thing with structs, that’s correct.
- deleted 2y ago[deleted]