SHARE
TWEET

Untitled

a guest Jun 16th, 2019 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fn bump_smaller(x: &mut i32, y: &mut i32) {
  2.     if *x <= *y {
  3.         *x += 1;
  4.     } else {
  5.         *y += 1;
  6.     }
  7. }
  8.  
  9. fn main() {
  10.     // example with variables
  11.     let mut x = 5;
  12.     let mut y = 6;
  13.     bump_smaller(&mut x, &mut y);
  14.     assert_eq!(x, y);
  15.  
  16.     // example with fields
  17.     struct Pair {
  18.         x: i32,
  19.         y: i32,
  20.     }
  21.     let mut pair = Pair { x: 5, y: 6 };
  22.     bump_smaller(&mut pair.x, &mut pair.y);
  23.     assert_eq!(pair.x, pair.y);
  24.  
  25.     // Getting two &mut references into a Vec is a little trickier. The obvious
  26.     // approach leads to a compiler error:
  27.     //     let mut vec = vec![5, 6];
  28.     //     bump_smaller(&mut vec[0], &mut vec[1]);
  29.     // error[E0499]: cannot borrow `vec` as mutable more than once at a time
  30.  
  31.     // example with Vec using split_at_mut
  32.     let mut vec = vec![5, 6];
  33.     let (left, right) = vec.split_at_mut(1);
  34.     bump_smaller(&mut left[0], &mut right[0]);
  35.     assert_eq!(vec[0], vec[1]);
  36.  
  37.     // example with Vec using a match pattern
  38.     let mut vec = vec![5, 6];
  39.     match &mut vec[..] {
  40.         [x, y] => bump_smaller(x, y),
  41.         _ => unreachable!(),
  42.     }
  43.     assert_eq!(vec[0], vec[1]);
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top