Hacker News new | ask | show | jobs
by Filligree 2446 days ago
You'll get a compile-time error explaining the situation, yes, including documentation links and possible fixes. The differences between the versions are minimal.

    fn add1(x: Thing) -> Thing {
      x + 1
    }

    fn add2(x: &Thing) -> Thing {
      x + 2
    }
This works on the assumption that whatever "+ 1" really means doesn't itself need ownership of x, e.g. because it mutates it. If it does, then you'll get an error. Or you could do this:

    fn add3(x: &mut Thing) {
      x.add(3)
    }
Which, presumably, modifies x instead of returning a copy. It's your job to make sure it makes sense to do that, but Rust has another trick in its pockets:

    let y = add1(x);  // Works; takes ownership.
    let z = add2(&y);  // Works, and doesn't take ownership.
    let zz = add2(&y);  // So you can do it twice. (Y tho?)
    let h = add3(&y);  // Compile-time error!
    let hh = add3(&mut y);  // Works. You need to specify that you're fine with y being mutated.