title: How can I get safe reference to existing object in Nim?
body: <p>I wrote a <a href="https://en.wikipedia.org/wiki/Nim_(programming_language)" rel="nofollow noreferrer">Nim</a> procedure taking two objects as <code>var</code> parameters. They each are an object with an <code>int</code> field <code>level</code>. Before doing the real work of the procedure, I want to put the parameters in order by which has the larger <code>level</code>, so I do this:</p>
  <pre><code>proc subroutine(param1: var MyObject, param2: var MyObject) =
    var large: ptr MyObject = param1.addr
    var small: ptr MyObject = param2.addr
  
    # If in wrong order by level, swap large and small
    if large.level &lt; small.level:
      large = param2.addr
      small = param1.addr
  
    # The rest of the proc references, only variables large and small, e.g.,
    large.level += 1
    small.level += 2
  </code></pre>
  <p>This seems to work for my application, but I notice that in the <a href="https://nim-lang.org/docs/manual.html#types-reference-and-pointer-types" rel="nofollow noreferrer">Nim documentation</a>, the <code>ptr</code> type is called &quot;unsafe&quot;, and it is suggested to be used only for low-level operations. There's a &quot;safe&quot; reference type <code>ref</code>, and it is suggested to use <code>ref</code> unless you really want to do manual memory management.</p>
  <p>I don't want to do manual memory management, and I want the Nim garbage collector to handle the memory for these parameters for me, but I don't see a way to get safe <code>ref</code>'s to the two parameters.</p>
  <p>I really want to be able to write the algorithm (which is significantly more complex than the simple code I showed) in terms of the variables <code>large</code> and <code>small</code>, rather than <code>param1</code> and <code>param2</code>. Otherwise, if I can only reference parameters <code>param1</code> and <code>param2</code>, without making these aliases for them, I'd have to copy and paste the same algorithm twice to separately handle the cases <code>param1.level &lt; param2.level</code> and <code>param1.level &gt;= param2.level</code>.</p>
  <p>Is there a more idiomatic Nim way to do something like this, without using a <code>ptr</code> type?</p>