Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Last active June 5, 2019 19:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save oconnor663/c6cf1cded48632971c109994cbd78637 to your computer and use it in GitHub Desktop.
interior pointers examples
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]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment