Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code, unused_variables)]
- /*
- I want to compare every item in a list to every other item in a list.
- If any pair match according to some criteria, I want to get a mutable
- reference to each object in the pair.
- */
- #[derive(Debug)]
- struct Stuff {}
- impl Stuff {
- fn compare(&self, other: &Stuff) -> bool {
- true // Placeholder
- }
- }
- // Some function requiring two mutable references
- fn do_something(stuff1: &mut Stuff, stuff2: &mut Stuff) {
- // Placeholder
- }
- /// Gets two mutable references to elements i and j in list
- fn get_pair<'a, T>(i: usize, j : usize, list: &'a mut [T]) -> (&'a mut T, &'a mut T) {
- let (a, b) = list.split_at_mut(j);
- let first = &mut a[i];
- let second = &mut b[0];
- (first, second)
- }
- fn do_it(list: &mut Vec<Stuff>) {
- // Find matching pairs and push their indices
- let mut matches : Vec<(usize, usize)> = Vec::new();
- for (i, stuff1) in list.iter().enumerate() {
- for (j, stuff2) in list[i..].iter().enumerate() {
- if stuff1.compare(stuff2) {
- matches.push((i, j));
- }
- }
- }
- // Get two mutable references by indices from list
- for m in matches.iter() {
- let (i, j) = m;
- let (stuff1, stuff2) = get_pair(*i, *j, list);
- do_something(stuff1, stuff2);
- }
- }
- fn main() {
- println!("Hello, world!");
- let mut list : Vec<Stuff> = Vec::new();
- do_it(&mut list);
- }
Add Comment
Please, Sign In to add comment