How can I implement the observer pattern in Rust?
<p>I have an observable collection and an observer. I want the observer to be a trait implementation of <code>trait Observer</code>. The observable object should be able to notify each observer when some event occurs. This should explain my intentions:</p>

<pre><code>struct A {
    observables: Vec&lt;Observable&gt;,
}

impl A {
    fn new() -&gt; A {
        A {
            observables: vec![],
        }
    }
}

trait Observer {
    fn event(&amp;mut self, _: &amp;String);
}

impl Observer for A {
    fn event(&amp;mut self, ev: &amp;String) {
        println!("Got event from observable: {}", ev);
    }
}

struct Observable {
    observers: Vec&lt;dyn Observer&gt;, // How to contain references to observers? (this line is invalid)
}

impl Observable {
    fn new() -&gt; Observable {
        Observable {
            observers: Vec::new(),
        }
    }

    fn add_observer(&amp;mut self, o: &amp;dyn Observer) {
        // incorrect line too
        self.observers.push(o);
    }

    fn remove_observer(&amp;mut self, o: &amp;dyn Observer) {
        // incorrect line too
        self.observers.remove(o);
    }

    fn notify_observers(&amp;self, ev: &amp;String) {
        for o in &amp;mut self.observers {
            o.event(ev);
        }
    }
}
</code></pre>

<p>(<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=7f7098ce3b8955d40fc1198b05aa8d3d" rel="noreferrer">Playground</a>)</p>

<p>I get the error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the size for values of type `(dyn Observer + 'static)` cannot be known at compilation time
  --&gt; src/lib.rs:24:5
   |
24 |     observers: Vec&lt;dyn Observer&gt;, // How to contain references to observers?
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `(dyn Observer + 'static)`
   = note: to learn more, visit &lt;https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait&gt;
   = note: required by `std::vec::Vec`
</code></pre>

<p>This is just a mock-up of what I want to do. I have code like this in Java, Python, and C++, but I don't know how to implement the observer pattern in Rust. I believe my problem is in storing a reference to observer objects inside observable objects.</p>