Hacker News new | ask | show | jobs
by legerdemain 1262 days ago
OK, simple issue that a beginning Rust user runs into immediately:

  - function arguments are moved into the called function

  - you can call a function with a ref, and then you can keep using it in the calling function, because there is a blanket impl of Copy for refs

  - you can call a function with a ref mut, and then you can keep using it in the calling function because ... ???
2 comments

Because when you pass by reference, you lend the value (or to phrase it the other way around: the function borrows the value). And so when the function’s done, it gives you the value back (because that’s how borrowing works, in the everyday sense of the word, as well as in th Rust sense)
This is either wrong or incomplete. When you call a function `f()` with some `&mut`, the callee gets a `&mut`, not a borrowed `&mut &mut`. The callee doesn't borrow the ref mut, it gets the actual ref mut, and for some time you have multiple mutable references in the same scope. How?
Because the calling function isn't using it at the time. Rust isn't proving something about the number of references in memory; it's proving something about the dynamic behaviour of the program, i.e. that there can be at most one reference actively being used to mutate it, at a time.

Hence there's no problem cloning a mutable reference implicitly, when calling a function. Notice that you can't for instance send it to another thread, however.

There are not multiple mutable references in the same scope. The mutable reference is only valid for the scope of the function `f()`. This doesn't sound like a problem understanding mutable references but a problem understanding scope.
It gets `&mut *&mut` (where * doesn't mean a pointer, just deref)

Not sure if that's good that this feature is automatic. Maybe it wouldn't be too bad to call functions like that for consistency:

    go_break_stuff(&mut *my_stuff_ref);
if you want to keep using the reference after the call.
The function isn’t borrowing the reference. It’s using the reference to borrow the value thats being pointed to by the reference.
I was looking for the word "reborrowing," which I think is crucial for beginners trying to form an effective mental model of Rust semantics.
You add '.clone()' or '&', the code compiles, you move on.