title: Capturing a local variable in a local function
body: <p>I have this maze-like thing with 2 points in it and I want the distance between those points through the maze. To do this I will use A* (unless there is a better algorithm I don't know about), but to use A* I need my <code>SN</code> (search node) struct to implement the <code>Ord</code> trait. I want to use the Manhattan distance from 1 location to another as heuristic, so I had code like this (<a href="https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=a31e5b5f6e34f8f1dd92db2e3d72cddc" rel="nofollow noreferrer">playground</a>):</p>
  <pre><code>use std::cmp::Ordering;
  
  fn main() {
      let something_i_need_in_cmp = 5;
  
      struct SN {
          loc: u16,
          step: u16,
      }
      
      impl Ord for SN {
          fn cmp(&amp;self, other: &amp;Self) -&gt; Ordering {
              let tc = self.step + something_i_need_in_cmp;
              let oc = other.step + something_i_need_in_cmp;
              tc.cmp(&amp;oc)
          }
      }
  }
  </code></pre>
  <p>This does not work because the <code>to</code> variable is not captured:</p>
  <pre class="lang-none prettyprint-override"><code>error[E0434]: can't capture dynamic environment in a fn item
    --&gt; src/main.rs:13:34
     |
  13 |             let tc = self.step + something_i_need_in_cmp;
     |                                  ^^^^^^^^^^^^^^^^^^^^^^^
     |
     = help: use the `|| { ... }` closure form instead
  
  error[E0434]: can't capture dynamic environment in a fn item
    --&gt; src/main.rs:14:35
     |
  14 |             let oc = other.step + something_i_need_in_cmp;
     |                                   ^^^^^^^^^^^^^^^^^^^^^^^
     |
     = help: use the `|| { ... }` closure form instead
  
  error[E0277]: can't compare `SN` with `SN`
     --&gt; src/main.rs:11:10
      |
  11  |     impl Ord for SN {
      |          ^^^ no implementation for `SN &lt; SN` and `SN &gt; SN`
      |
      = help: the trait `PartialOrd` is not implemented for `SN`
  
  error[E0277]: the trait bound `SN: Eq` is not satisfied
     --&gt; src/main.rs:11:10
      |
  11  |     impl Ord for SN {
      |          ^^^ the trait `Eq` is not implemented for `SN`
  </code></pre>
  <p>Is there any way around this?</p>
  <ol>
  <li><p>The error hints <code>use the `|| { ... }` closure form instead</code>, but I don't seem to be able to get this right. Can this help fix it?</p>
  </li>
  <li><p>An answer I found online suggested to add the extra data (the <code>to</code> variable in my case) to the struct (here <code>SN</code> but for searching like this that would mean that the <code>to</code> variable (or a reference to it) is copied a 100 times, which is not efficient.</p>
  </li>
  </ol>