Skip to content

Instantly share code, notes, and snippets.

@phaylon phaylon/main.rs Secret
Created Aug 14, 2018

Embed
What would you like to do?
Match Ergonomics Issue C: Semantic Convention Enforcement
#![allow(dead_code, unused, unreachable_patterns)]
enum State {
CaseCopy { v: i32 },
CaseSingle { v: Vec<i32> },
CaseMulti { v1: Vec<i32>, v2: Vec<i32> },
CaseComplex { flag: bool, v1: Vec<i32>, v2: Vec<i32> },
}
fn handle(state: &mut State) {
// cases following convention
match *state {
State::CaseCopy { v } => println!("copied something out"),
State::CaseSingle { ref v } => println!("not mutating the v"),
State::CaseSingle { ref mut v } => println!("actually mutatint the v"),
State::CaseMulti { ref mut v1, ref v2 } => println!("only mutating one of them"),
State::CaseComplex { flag: true, ref mut v1, ref v2 } => println!("mut first"),
State::CaseComplex { flag: false, ref v1, ref mut v2 } => println!("mut second"),
}
// not following convention
// accidental mutation is hard to discover
match state {
State::CaseSingle { v } => println!("not actually copying out"),
State::CaseMulti { v1, v2 } => println!("also not copying out"),
_ => (),
}
// following convention with accidental mutation
match state {
// if you only expected one mutation, the second one is easier to notice
State::CaseMulti { ref mut v1, ref mut v2 } => println!("accidentally mutate both"),
_ => (),
}
}
fn main() {
let mut state = State::CaseCopy { v: 23 };
handle(&mut state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.