(no title)
sfteus | 3 years ago
The "typical" Go nil-check would usually look something like this (no idea how code will look, apologies up front):
result, err := someFunction()
if err != nil { ...
It's nice that you're not having to litter your code with try/catch statements, or use a union type with an error value like in other languages, but the downside is that Go only checks to see whether err is used at some point (or makes you replace it with _), and it's possible to accidentally use err in a read-context and skip actually checking the value. Go won't prompt you that the error case is unhandled (in my experience)
In Rust, when you want to return a null-like value (None), you wrap it in Option<type>. To the compiler, Option<type> is a completely separate type, and it will not allow you to use it anywhere the interior type is expected until the option is unwrapped and the possible null value is handled. You'd do that like this:
var result = some_function()
match result {
Some(x) => handle_value(x),
None => handle_null(),
}The compiler forces you to unwrap result into its two possible underlying types (any possible <type> or None), and handle each case, which prevents an accidental null value being passed to handle_value. Trying to pass result directly into handle_value would give you a type check error, since it's expecting a <type> but is passed an Option<type>. The compiler will also give you an error if you try to only handle the Some(x) path without providing a case for None as well, so you can't just accidentally forget to handle the null case.
(For completeness, you can also just do result.unwrap() to get the inner value and panic if it is None, which can be useful in some cases like when you know it will always be filled, and you want to fully terminate if it somehow isn't).
So in your case (assuming this is in the context of a video game), you'd make score an Option<i32> for example, then unwrap it when you needed the actual value. Generally speaking, I'd make the score returned from a saved game loading function be Option<i32> and make the actual score for the current session just an i32, then the function that handles loading a game save into the current session would handle the Option<i32> from the save file (defaulting to 0 when this is None), and we could assume that the score would be set by the time the game session is running so we don't have to constantly unwrap it within the game logic itself.
No comments yet.