Guest User

Untitled

a guest
Dec 12th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. #![allow(dead_code, unused_variables)]
  2. /*
  3. I want to compare every item in a list to every other item in a list.
  4. If any pair match according to some criteria, I want to get a mutable
  5. reference to each object in the pair.
  6.  
  7. */
  8.  
  9. #[derive(Debug)]
  10. struct Stuff {}
  11.  
  12. impl Stuff {
  13. fn compare(&self, other: &Stuff) -> bool {
  14. true // Placeholder
  15. }
  16. }
  17.  
  18. // Some function requiring two mutable references
  19. fn do_something(stuff1: &mut Stuff, stuff2: &mut Stuff) {
  20. // Placeholder
  21. }
  22.  
  23. /// Gets two mutable references to elements i and j in list
  24. fn get_pair<'a, T>(i: usize, j : usize, list: &'a mut [T]) -> (&'a mut T, &'a mut T) {
  25. let (a, b) = list.split_at_mut(j);
  26.  
  27. let first = &mut a[i];
  28. let second = &mut b[0];
  29.  
  30. (first, second)
  31. }
  32.  
  33. fn do_it(list: &mut Vec<Stuff>) {
  34.  
  35. // Find matching pairs and push their indices
  36. let mut matches : Vec<(usize, usize)> = Vec::new();
  37. for (i, stuff1) in list.iter().enumerate() {
  38. for (j, stuff2) in list[i..].iter().enumerate() {
  39. if stuff1.compare(stuff2) {
  40. matches.push((i, j));
  41. }
  42. }
  43. }
  44.  
  45. // Get two mutable references by indices from list
  46. for m in matches.iter() {
  47. let (i, j) = m;
  48. let (stuff1, stuff2) = get_pair(*i, *j, list);
  49. do_something(stuff1, stuff2);
  50.  
  51. }
  52. }
  53.  
  54. fn main() {
  55. println!("Hello, world!");
  56.  
  57. let mut list : Vec<Stuff> = Vec::new();
  58. do_it(&mut list);
  59. }
Add Comment
Please, Sign In to add comment