DRY (Don’t Repeat Yourself)
Macros allow writing DRY code by factoring out the common parts of functions
and/or test suites. Here is an example that implements and tests the +=, *=
and -= operators on Vec<T>:
1. use std::ops::{Add, Mul, Sub};
3. macro_rules! assert_equal_len {
4. // The `tt` (token tree) designator is used for
5. // operators and tokens.
6. ($a:ident, $b: ident, $func:ident, $op:tt) => (
7. assert!($a.len() == $b.len(),
8. "{:?}: dimension mismatch: {:?} {:?} {:?}",
9. stringify!($func),
10. ($a.len(),),
11. stringify!($op),
12. ($b.len(),));
13. )
14. }
16. macro_rules! op {
17. ($func:ident, $bound:ident, $op:tt, $method:ident) => (
18. fn $func<T: $bound<T, Output=T> + Copy>(xs: &mut Vec<T>, ys: &Vec<T>) {
19. assert_equal_len!(xs, ys, $func, $op);
21. for (x, y) in xs.iter_mut().zip(ys.iter()) {
22. *x = $bound::$method(*x, *y);
23. // *x = x.$method(*y);
24. }
25. }
26. )
27. }
29. // Implement `add_assign`, `mul_assign`, and `sub_assign` functions.
30. op!(add_assign, Add, +=, add);
31. op!(mul_assign, Mul, *=, mul);
32. op!(sub_assign, Sub, -=, sub);
34. mod test {
35. use std::iter;
36. macro_rules! test {
37. ($func: ident, $x:expr, $y:expr, $z:expr) => {
38. #[test]
39. fn $func() {
40. for size in 0usize..10 {
41. let mut x: Vec<_> = iter::repeat($x).take(size).collect();
42. let y: Vec<_> = iter::repeat($y).take(size).collect();
43. let z: Vec<_> = iter::repeat($z).take(size).collect();
45. super::$func(&mut x, &y);
47. assert_eq!(x, z);
48. }
49. }
50. }
51. }
53. // Test `add_assign`, `mul_assign` and `sub_assign`
54. test!(add_assign, 1u32, 2u32, 3u32);
55. test!(mul_assign, 2u32, 3u32, 6u32);
56. test!(sub_assign, 3u32, 2u32, 1u32);
57. }
1. $ rustc --test dry.rs && ./dry
2. running 3 tests
3. test test::mul_assign ... ok
4. test test::add_assign ... ok
5. test test::sub_assign ... ok
7. test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured
