title: Create vector of objects implementing a trait in Rust
body: <p>In Java-speak, I am trying to create a collection (vector) of objects (strict instances), each one of which implements an interface (trait), so I can then iterate over the collection and call a method on all of them.</p>
  
  <p>I have reduced it down to one sample file below which contains all the parts that I hope will make it easier to get answers.</p>
  
  <pre><code>// main.rs - try and compile using just "rustc main.rs"
  use std::io::Result;
  
  /// ////// Part 1
  // Types used by implementors of the trait, and in creating a vector of implementors of the trai
  pub struct SampleResult {
      metric: String,
  }
  
  pub trait SampleRunner {
      fn run(&amp;self, &amp;'static str) -&gt; Result&lt;SampleResult&gt;;
  }
  
  pub struct Sample {
      name: &amp;'static str,
      runner: &amp;'static SampleRunner,
  }
  
  /// /////// Part 2
  /// Create one specific static instance of such as Sample
  static SAMPLE1: Sample = Sample {
      name: "sample",
      runner: &amp;Sample1,
  };
  
  // need a struct to hold the run method to satisfy the trait???
  struct Sample1;
  
  // Implement the trait for this specific struct
  impl SampleRunner for Sample1 {
      fn run(&amp;self, name: &amp;'static str) -&gt; Result&lt;SampleResult&gt; {
          println!("Name: {}", name);
          Ok(SampleResult { metric: "OK".to_string() })
      }
  }
  
  /// /////// Part 3
  /// Using the existing static instances of Sample struct, by creating a vector of references for them
  /// then iterating over the vector and calling the trait method on each one
  fn main() {
      let sample_set: Vec&lt;&amp;Sample&gt; = vec![&amp;SAMPLE1];
  
      for sample in sample_set.iter() {
          match sample.runner.run(sample.name) {
              Ok(result) =&gt; println!("Success"),
              _ =&gt; panic!("failed"),
          }
      }
  }
  </code></pre>
  
  <p>That particular example fails with the message:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `SampleRunner + 'static: std::marker::Sync` is not satisfied in `Sample`
    --&gt; &lt;anon&gt;:21:1
     |
  21 |   static SAMPLE1: Sample = Sample {
     |  _^ starting here...
  22 | |     name: "sample",
  23 | |     runner: &amp;Sample1,
  24 | | };
     | |__^ ...ending here: within `Sample`, the trait `std::marker::Sync` is not implemented for `SampleRunner + 'static`
     |
     = note: `SampleRunner + 'static` cannot be shared between threads safely
     = note: required because it appears within the type `&amp;'static SampleRunner + 'static`
     = note: required because it appears within the type `Sample`
     = note: shared static variables must have a type that implements `Sync`
  </code></pre>
  
  <p>But I have had many different problems depending on the approach I have taken, related to <code>Sync</code>, <code>Sized</code>, etc etc.</p>