title: What is the idiomatic Rust way to copy/clone a vector in a parameterized function?
body: <p>I'm trying to write a parameterized function that takes an immutable vector, clones or copies it, does something to the new vector (such as shuffle it) and returns it as a new owned vector.  How can this be done and what is the most idiomatic way to do it? </p>
  
  <p><strong>Attempt #1</strong></p>
  
  <pre><code>pub fn shuffle&lt;T&gt;(vec: &amp;mut [T]) {
      // ... contents removed: it shuffles the vector in place
      // ... so needs a mutable vector
  }
  
  pub fn shuffle_create_new&lt;T: Clone&gt;(vec: &amp;[T]) -&gt; Vec&lt;T&gt; {
      let mut newvec = vec.clone();
      shuffle(&amp;mut newvec);
      return newvec.to_owned();
  }
  </code></pre>
  
  <p>Fails with:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0596]: cannot borrow immutable borrowed content as mutable
   --&gt; src/main.rs:8:13
    |
  8 |     shuffle(&amp;mut newvec);
    |             ^^^^^^^^^^^ cannot borrow as mutable
  </code></pre>
  
  <p>even though I declared <code>newvec</code> as mutable.  I don't understand why.</p>
  
  <p><strong>Attempt #2</strong></p>
  
  <pre><code>pub fn shuffle_owned&lt;T: Clone&gt;(mut vec: Vec&lt;T&gt;) -&gt; Vec&lt;T&gt; {
      shuffle(&amp;mut vec);
      return vec;
  }
  </code></pre>
  
  <p>While this compiles, it doesn't do what I want.  The vector you pass into <code>shuffle_owned</code> gets <strong>moved</strong> into the function, shuffled and then has its ownership transferred back to the caller (via the return value).  So the original vector is <em>modified</em>.</p>
  
  <p>I want to know how to pass in a vector that will <strong>not</strong> be mutated, but have the values cloned into a new boxed vector and returned when finished - as you do in a functional programming language that has immutable data (such as Clojure).</p>