title: Understanding refs in D language
body: <p>Say, I want to add two vectors (in a mathematical sense) of something numerical. Naturally I'd do something like:</p>
  
  <pre><code>T[] add(T)(T[] a, T[] b) {
      assert(a.length == b.length);
      T[] res = a.dup;
      foreach (i; 0 .. a.length) {
          res[i] = a[i] + b[i];
      }
     return res;
  }
  </code></pre>
  
  <p>Well, it's ok, but I suspect <code>a</code> and <code>b</code> copying every call, which is not so great. So I declare them <code>ref</code>.</p>
  
  <pre><code>T[] add(T)(ref T[] a, ref T[] b) { ...
  </code></pre>
  
  <p>It works nice while passing variables, but for a test I use array instances:</p>
  
  <pre><code>assert(add([1, 2, 3], [4, 5, 6]) == [5, 7, 9]);
  </code></pre>
  
  <p>And this fails as it can't deduce refs for arrays. I've managed to figure out a workaround:</p>
  
  <pre><code>T[] add(T)(T[] a, T[] b) {
      return add(a, b);
  }
  </code></pre>
  
  <p>Which seems to solve the problem, but looks rather silly. What is the better design for my problem?</p>
  
  <p>Or putting it into smaller questions: do I really have to declare arguments as <code>ref</code> to avoid copying? Could the compiler, as I don't modify <code>a</code> and <code>b</code>, optimize this for me? How'd I declare arguments immutable by the way (I tried <code>immutable</code> keyword, looks like I'm using it wrong)? Would <code>res</code> be really copied twice in the workaround, or returns are made through move?</p>