4 ms·
Non-nullable types in are implemented using a combination of (powerful) enumeration types and generics. Enumeration types in rust can be the usual ones you fin
by otikik 7y ago
Non-nullable types in are implemented using a combination of (powerful) enumeration types and generics.
Enumeration types in rust can be the usual ones you find in other languages:
enum UserStatus {
Anonymous,
Registered,
Confirmed,
}
But their variants are not limited to names, they can be other things[1]:
enum UserStatus {
Anonymous,
Registered{ email: Email, date: Date }, // a struct
Confirmed(date), // a tuple
}
Enum types can also be made generic. For example the Date type could be a parameter in the example above:
enum UserStatus<T> {
Anonymous,
Registered{ email: Email, date: T }, // a struct
Confirmed(T), // a tuple
}
Which brings us to the Option type[2] in rust. It is an Enum with a generic type attribute, defined like this:
enum Option<T>
{
Some(T), // a tuple with a single item of type T
None,
}
In rust, when a function says it returns an `i32`, it will always return an `i32`. It never returns `i32 or null`.
If you want not return an `i32` sometimes, you must specify exactly what else it can be. It is often convenient to return an Option<i32> instead. Then it can return `Some(i32)` or `None`. The difference with the "implicit null" from before is that the compiler will force you to "deconstruct the option safely", in compile time. You will never get a "Null Pointer Exception" in run time because of this.
For me, this is huge, and one of the reasons I like Rust more than Go.
[1]: https://doc.rust-lang.org/rust-by-example/custom_types/enum.html https://doc.rust-lang.org/rust-by-example/custom_types/enum....
[2]: https://doc.rust-lang.org/std/option/ https://doc.rust-lang.org/std/option/