Type-Level Programming in Rust
I&#x27;m immediately turned off by the entirely gratuitous use of unsafe here.  I clicked through to the linked Reddit discussion and I&#x27;m not convinced the author has really thought it through.  Writing, &quot;pedagogically, that&#x27;s irrelevant to the post, so I didn&#x27;t highlight it&quot; misunderstands the pedagogy here.<p>However, there&#x27;s some really neat stuff later, so it&#x27;s wise to grit your teeth and get past it.<p>In case anyone else had the same reaction, here&#x27;s an entirely-safe version of the first snippet that you can pretend replaced the original:<p><pre><code>    &#x2F;&#x2F; Each state is a unique type
    struct Receiving;
    struct Sending;

    &#x2F;&#x2F; The state machine is parameterized by the state
    struct Channel&lt;State&gt; {
      chan: ...,
      _state: PhantomData&lt;State&gt;
    }

    &#x2F;&#x2F; Methods for the state are uniquely associated with only the state
    impl Channel&lt;Receiving&gt; {
      &#x2F;&#x2F; recv consumes ownership, ensuring old state is invalidated
      fn recv(mut self) -&gt; (Channel&lt;Sending&gt;, String) {
        let Channel { chan, .. } = self;
        let msg = chan.recv();
        &#x2F;&#x2F; The state type changes after executing a transition
        let next = Channel { chan, _state: PhantomData };
        (next, msg)
      }
    }

    impl Channel&lt;Sending&gt; {
      fn send(mut self, msg: String) -&gt; Channel&lt;Receiving&gt; {
        let Channel { chan, .. } = self;
        chan.send(msg);
        Channel { chan, _state: PhantomData }
      }
    }

    #[test]
    fn channel_test() {
      let c: Channel&lt;Sending&gt; = Channel::new();
      let c: Channel&lt;Receiving&gt; = c.send(&quot;hi&quot;);
      let (c, msg) = c.recv();
      &#x2F;&#x2F; and so on
    }</code></pre>