Hacker News new | ask | show | jobs
by saagarjha 2446 days ago
Consider the following code:

  fn add1(x: Vec<i32>) -> Vec<i32> { // Takes ownership
      return x.iter().map(|&x| x + 1).collect::<Vec<_>>();
  }
  
  fn add1_borrow(x: &Vec<i32>) -> Vec<i32> {
      return x.iter().map(|&x| x + 1).collect::<Vec<_>>();
  }
The first will take ownership of the thing you pass in, so you can't do something like this:

  let x = vec![1, 2, 3];
  let y = add1(x);
  let z = add1(x); // error[E0382]: use of moved value: `x`
but the follow code is OK, because the function just borrows the value instead of owning (and destroying) it:

  let x = vec![1, 2, 3];
  let y = add1_borrow(&x);
  let z = add1_borrow(&x);
This is legal too:

  let x = vec![1, 2, 3];
  let y = add1_borrow(&x);
  let z = add1(x);
but as before you can't use x after this.

(Note, I chose Vec here because Vec does not implement Copy: if I used i32 it would just copy the value in the non-borrowing case, which would make the code fine as no ownership would be transferred.)