by tedunangst · 4y ago · 0 comments
Well, yeah, if something may or may not be there, you have to check before you use it. How else do people want it to work?
The salient rebuttal is that this pattern is a strong hint to check, whereas a pointer is ambiguous (it's unclear whether or not a bare pointer may ever be nil, but you would only use this pattern to be explicit that a check is needed). This pattern can also support value types so you don't have to worry as much about unnecessary allocations.
(But thanks, I overlooked T? conversions inside if.)
At any boundary where something might be null, you do the null check. If it's null, you do whatever logic is necessary right there and only right there. That might be to skip the computation, to use a default value, to get the value from somewhere else, to return an error, or whatever. If it's not null, you use the internal value and from then on every user can operate on a guarantee that it's not null.
> Tell me more about these unexplodable languages.
I don't think anyone else mentioned an entire language being unexplodable, just a pointer type.
Later on the thread you talk about `Option` in Rust, which is not what I think most people would consider a pointer type, but even if it is, it's certainly not the only one. I think GP was talking about the basic reference type (i.e. `&T`), which will not ever be null in safe code, so dereferencing it will not explode.
I am a Rust novice but I have not found a way to get to uninitialised memory in safe Rust. Yet.
Yes you can: https://doc.rust-lang.org/std/ptr/fn.null.html
You just won't use it unless you're doing FFI or similar things.