Skip to content

Instantly share code, notes, and snippets.

@bingo347
Last active July 4, 2019 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingo347/784cfbbbc4215aad92131ae17af73559 to your computer and use it in GitHub Desktop.
Save bingo347/784cfbbbc4215aad92131ae17af73559 to your computer and use it in GitHub Desktop.
Rust macro for mutate immutable variables
macro_rules! mutate {
($($var:ident),+ $code:block) => {
let ($($var,)+) = {
let ($(mut $var,)+) = ($($var,)+);
$code;
($($var,)+)
};
};
}
#[cfg(test)]
mod tests {
#[test]
fn can_mutate_single() {
let s = String::new(); // s is immutable empty String
mutate!(s { s.push_str("test"); }); // mutate in macro
assert_eq!("test", &s[..]);
}
#[test]
fn can_mutate_multy() {
let s0 = String::new();
let s1 = String::new();
mutate!(s0, s1 {
s0.push_str("test0");
s1.push_str("test1");
});
assert_eq!("test0", &s0[..]);
assert_eq!("test1", &s1[..]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment