Last active
July 4, 2019 03:45
-
-
Save bingo347/784cfbbbc4215aad92131ae17af73559 to your computer and use it in GitHub Desktop.
Rust macro for mutate immutable variables
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
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