Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn bump_smaller(x: &mut i32, y: &mut i32) {
- if *x <= *y {
- *x += 1;
- } else {
- *y += 1;
- }
- }
- fn main() {
- // example with variables
- let mut x = 5;
- let mut y = 6;
- bump_smaller(&mut x, &mut y);
- assert_eq!(x, y);
- // example with fields
- struct Pair {
- x: i32,
- y: i32,
- }
- let mut pair = Pair { x: 5, y: 6 };
- bump_smaller(&mut pair.x, &mut pair.y);
- assert_eq!(pair.x, pair.y);
- // Getting two &mut references into a Vec is a little trickier. The obvious
- // approach leads to a compiler error:
- // let mut vec = vec![5, 6];
- // bump_smaller(&mut vec[0], &mut vec[1]);
- // error[E0499]: cannot borrow `vec` as mutable more than once at a time
- // example with Vec using split_at_mut
- let mut vec = vec![5, 6];
- let (left, right) = vec.split_at_mut(1);
- bump_smaller(&mut left[0], &mut right[0]);
- assert_eq!(vec[0], vec[1]);
- // example with Vec using a match pattern
- let mut vec = vec![5, 6];
- match &mut vec[..] {
- [x, y] => bump_smaller(x, y),
- _ => unreachable!(),
- }
- assert_eq!(vec[0], vec[1]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement