M
Modular2mo ago
name

Does Mojo have a null safety feature like Dart?

Sound null safety
Information about Dart's null safety feature
9 Replies
Darkmatter
Darkmatter2mo ago
Aside from UnsafePointer, which needs to be nullable for C interop, Mojo does not have null. You use Optional instead.
Heyitsmeguys
Heyitsmeguys2mo ago
Mojo does not have null
Doesn't None act as Mojo's null?
Darkmatter
Darkmatter2mo ago
None is its own type, which is mostly used for "there is nothing here". Types don't have the implicit "There may or may not be something here" union that many languages have which leads to null safety issues. None can be cast into an Optional without a value in it, but this means that unless a function returns Optional[T], it will always return a valid instance of T. A function can also return None, meaning no return type, which is useful for generics.
name
nameOP2mo ago
@Owen Hilyard can you check this issue: https://github.com/modular/mojo/issues/3977
GitHub
[BUG] Mojo compiler and language server should detect and prevent c...
Bug description Currently, the following Mojo code compiles successfully but leads to a runtime error when executed. Error message: .value() on empty Optional Instead of requiring explicit checks f...
Darkmatter
Darkmatter2mo ago
Optional is intended for runtime checks. The documentation for Optional.value states: "If you call this without first verifying the optional with bool() eg. by if my_option: or without otherwise knowing that it contains a value (for instance with or_else), the program will abort." Due to a lack of pattern matching, there isn't a way to enforce the check right now, but that is coming. The issue you show is a trivial one, but a more realistic example would be something like the presence of a CLI flag, or whether the user's IP address geolocates to a city who's name starts with X. There's no way to tell that at compile time, so Mojo can't tell you it's None. What you've done here is roughly equivalent to using a language with null safety and ignoring the result of the null check.
name
nameOP2mo ago
Thanks for the reply. The suggestion is that the compiler should handle this instead of the programmer having to check for the value's existence manually. Let's wait for pattern matching to arrive.
Darkmatter
Darkmatter2mo ago
What I would suggest for now is to not use Optional unless you want to check for the absence of the value, then the compiler will give errors like you want if someone tries to use None.
Pun
Pun2mo ago
The compiler handles it by the fact null doesn't exist But I see compile time handling of optional isn't implemented. For instance Rust does force the programmer to handle optionals
Darkmatter
Darkmatter2mo ago
.value() is .unwrap() A lack of pattern matching means we can't have more for now.

Did you find this page helpful?