Created
August 18, 2020 19:15
-
-
Save FeezyHendrix/61bce4e029383530b144fb36197bdab2 to your computer and use it in GitHub Desktop.
Enums and Options in Rust
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
// Allow for rust to recognized unused code | |
#[!allow(dead_code)] | |
// Allow rust to be able to debug enum | |
#[derive(Debug)] | |
// Direction enum that each type is type of struct (Point) | |
enum Direction { | |
Up(Point), | |
Down(Point), | |
Left(Point), | |
Right(Point) | |
} | |
#[derive(Debug)] | |
// Keys enum | |
enum Keys { | |
UpKey(String), | |
DownKey(String), | |
LeftKey(String), | |
RightKey(String) | |
} | |
// Create an impl for the enum direction to be able to assign functions to them | |
// More like a class with methods. | |
// For each enum you select in the direction enum | |
// You can match them | |
impl Direction { | |
fn match_direction(&self) -> Keys { | |
match *self { | |
Direction::Up(_) => Keys::UpKey(String::from("Pressed w")), | |
Direction:: Down(_) => Keys::DownKey(String::from("Pressed s")), | |
Direction:: Left(_) => Keys::LeftKey(String::from("Pressed a")), | |
Direction:: Right(_) => Keys::RightKey(String::from("Pressed d")) | |
} | |
} | |
} | |
// Implementation of method relation to the Keys enum | |
impl Keys { | |
fn destruct (&self) -> &String { | |
match *self { | |
Keys::UpKey(ref s) => s, | |
Keys::DownKey(ref s) => s, | |
Keys::LeftKey(ref s) => s, | |
Keys: RightKey(ref s) => s | |
} | |
} | |
} | |
// Struct Point | |
#[derive(Debug)] | |
struct Point { | |
x: i32, | |
y: i32 | |
} | |
// Main Bitches! | |
fn main() { | |
let u = Direction::Up(Point { x: 0, y: 1}); | |
let k = u.match_direction(); | |
println!("{:?}", k); | |
} |
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
// Options take in a genetic type of Some<T> or None | |
// An example of the division which returns an option of either Some or None | |
fn division(x: f64, y: f64) -> Option<f64> { | |
if y == 0.0 { | |
None | |
} else { | |
Some(x / y) | |
} | |
} | |
fn main() { | |
// assign the option to a variable | |
let res = division(10.0, 6.0); | |
// Match the result to either Some or None | |
match res { | |
Some(x) => println!("{}", x), | |
None => println!("Cannot divide by 0") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment