SHARE
TWEET

Untitled

a guest Jul 18th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Wrapper holding (amoung other things) a vec of entries
  2. // as well as some values that are constant for all entries
  3. struct Wrapper {
  4.     entries: Vec<Entry>,
  5.     some_values_constant_for_all_entries: Vec<usize>
  6. }
  7.  
  8. impl Wrapper {
  9.     pub fn new() -> Self {
  10.         let mut entries = Vec::with_capacity(3);
  11.         for val in 0..3 {
  12.             entries.push(Entry { val });
  13.         }
  14.         Wrapper {
  15.             entries,
  16.             some_values_constant_for_all_entries: vec![1,2,4]
  17.         }
  18.     }
  19.  
  20.     pub fn entries_mut(&mut self) -> &mut Vec<Entry> {
  21.         &mut self.entries
  22.     }
  23.    
  24.     pub fn constant_values(&self) -> &Vec<usize> {
  25.         &self.some_values_constant_for_all_entries
  26.     }
  27. }
  28.  
  29. // Entry holding a value (and various other things)
  30. struct Entry {
  31.     val: usize
  32. }
  33.  
  34. impl Entry {
  35.     pub fn update_val(&mut self, update_value: usize, constant_values: &Vec<usize>) {
  36.         //update value based off the update_value and constant_values
  37.     }
  38.  
  39.     pub fn val(&self) -> usize {
  40.         self.val
  41.     }
  42. }
  43.  
  44. // implementations of the trait define how the values get updated
  45. trait MyTrait {
  46.     fn calculate_update_value(&self, wrapper: &mut Wrapper);
  47. }
  48.  
  49. struct SomeImpl {
  50.     some_val: usize
  51. }
  52.  
  53. impl MyTrait for SomeImpl {
  54.     fn calculate_update_value(&self, wrapper: &mut Wrapper) {
  55.         for entry in wrapper.entries_mut().iter_mut() {
  56.             let val = entry.val % self.some_val;
  57.             entry.update_val(val, wrapper.constant_values());
  58.         }
  59.     }
  60. }
  61.  
  62. struct Algorithm<T> where T: MyTrait {
  63.     wrapper: Wrapper,
  64.     implementation: T
  65. }
  66.  
  67. impl<T> Algorithm<T> where T: MyTrait {
  68.     fn update(&mut self) {
  69.         self.implementation.calculate_update_value(&mut self.wrapper);
  70.     }
  71. }
  72.  
  73.  
  74.  
  75. fn main() {
  76.     let wrapper = Wrapper::new();
  77.     let implementation = SomeImpl { some_val: 5 };
  78.     let mut algorithm = Algorithm {wrapper, implementation};
  79.     algorithm.update();
  80. }
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