> Ah, but what makes it an invalid reference, apart from convention?It's an invalid reference in that a reference which does not refer to an object is either dead code, or an unrecoverable error.
There's no point in checking if a reference refers to null, because (unlike pointers) it cannot then be assigned a useful value, and also because any such check will be removed by the optimizer, because null references are undefined behavior (in both C++[1] and Rust[2]).
> Indeed, though in Rust (like most other safe-by-default languages) you do need that glaringly obvious "unsafe" keyword to perform the conversion, which is a hint that you should be checking for null at that point.
It is an improvement but (obviously) the unsafety in this case escapes from the "unsafe" block into the surrounding "safe" code and other "safe" functions.
It's also possible, even in entirely-"safe" code, to crash a Rust program by attempting to dereference a null pointer.
fn dereference(nullable_ref: Option<&i32>) -> &i32 {
nullable_ref.unwrap()
}
fn crash() {
dereference(None);
}
[1]
https://godbolt.org/g/TjexTp[2] https://godbolt.org/g/eeXAnn