title: How do I write a function that adds an element to a vector, allowing the element to be changed before insertion?
body: <p>I'm trying to make a simple example involving a vector of structs to learn Rust. All examples of vectors in the Rust literature I've found only use vectors of integers.</p>
  
  <p>I want to write a function aimed at filling a vector, allowing the possibility of the element to be inserted to be changed, I can't figure out what to do. I always got a compiler <code>error[E0308]: mismatched types</code> on 
  the <code>push</code> method, because <code>elem</code> is a reference to a <code>Point</code>. So</p>
  
  <ul>
  <li><code>push()</code> needs a <code>Point</code> structure because <code>v</code> is a vector of <code>Point</code></li>
  <li>but if I want to modify <code>elem</code>, I need to pass a (mutable?) reference</li>
  </ul>
  
  <p>What is the right thing to do?</p>
  
  <pre><code>// structure used everywhere in Rust examples
  #[derive(Debug)]
  struct Point {
      x: i16,
      y: i16
  }
  
  fn add_element(v: &amp;mut Vec&lt;Point&gt;, elem: &amp;Point) {
      // modify element
      elem.x = 0;
  
      // add element
      v.push(elem);
  }
  
  // this example is meant to study a vector of structs
  fn main() {
      // declare 2 points. By default, live on the stack
      let origin = Point {x:0, y:0};
      println!("origin address\t: {:p}", &amp;origin);
      let mut p1 = Point {x:1, y:1};
      println!("p1 address\t: {:p}", &amp;p1);    
  
      // declare a new vector of structs. Allocation is made in the heap
      // declare mutable because we'll add elements to vector
      let mut v: Vec&lt;Point&gt; = Vec::new();
  
      // add points
      add_element(&amp;mut v, &amp;origin);
      add_element(&amp;mut v, &amp;p1);    
  
      // change p1
      p1.x = 2;
      p1.y = 2;
  }
  </code></pre>