Last active
October 13, 2018 02:07
-
-
Save nestoralonso/50a5a0890502fa60a79a2857f0e2d02c to your computer and use it in GitHub Desktop.
Rust Pattern matching Sample
This file contains hidden or 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 Action { | |
_type: String, | |
amount: u32 | |
} | |
fn update_counter(state:u32, action: Action) -> u32 { | |
let Action {_type, amount} = action; | |
println!("{} {} {}", _type, amount, state); | |
return match _type.as_str() { | |
"INCREMENT" => state + amount, | |
"DECREMENT" => state - amount, | |
"RESET" => 0, | |
_ => state | |
}; | |
} | |
fn main() { | |
let action = Action { | |
_type: "INCREMENT".to_string(), | |
amount: 2 | |
}; | |
let new_state = update_counter(4, action); | |
println!("{:?}", new_state); // 6 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment