Last active
June 5, 2019 19:45
Star
You must be signed in to star a gist
interior pointers examples
This file contains 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
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