Skip to content

Instantly share code, notes, and snippets.

@nestoralonso
Last active October 13, 2018 02:07
Show Gist options
  • Save nestoralonso/50a5a0890502fa60a79a2857f0e2d02c to your computer and use it in GitHub Desktop.
Save nestoralonso/50a5a0890502fa60a79a2857f0e2d02c to your computer and use it in GitHub Desktop.
Rust Pattern matching Sample
#[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