Created
August 22, 2016 10:23
-
-
Save KodrAus/03108312df3ac43108f965adc9cb2d43 to your computer and use it in GitHub Desktop.
Rust Option
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug)] | |
struct Data; | |
//By default, variables must have a value | |
//Option<T> lets you explicitly bind to 'None' | |
fn might_be_null(input: bool) -> Option<Data> { | |
if input { | |
Some(Data) | |
} | |
else { | |
None | |
} | |
} | |
fn main() { | |
let not_null = might_be_null(false); | |
//You have to match on your result to see what it contains | |
match not_null { | |
Some(data) => println!("told you: {:?}", data), | |
None => println!("It was null all along!? I'm so lucky Rust has my back!") | |
} | |
//You can also use helpers like 'is_some', 'ok_or', 'map' etc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment