Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It is perfect fine to take by value something that is not Copy to transfer its ownership.

It is a compiler error to use the value after it was moved. And the compiler error is quite explicit about how to solve it

For example you can explicitly clone

    let y = add(x.clone());
    let z = add(x);


What would be cases where the add() function need ownership of the x?

What the chance in real life that a function like that cannot simply use a reference?

In my learning Rust, my life became significantly better and easier when I started to references to borrow as much as possible.


That was just an example. But maybe 'x' is a BigInt type that use a memory allocation to store its contents. The ownership would be transferred to the return value


But again, what would be the drawback(s) of using a pointer instead of transfering the ownership?

Not rethorical, I'm genuinely curious as I used to struggle with the copy vs move decisions, and a bunch of issues with ownership which went all away when I started using pointer/borrowing everywhere.


The downside to using a mutable reference instead of passing around ownership is just that it would be awkward.

You'd have to write two extra lines of code to set up y and z separately from calling add(), and you'd have to make them mutable which is an extra mental burden.

And an immutable reference is bad because it would force extra objects to be allocated, wasting time and cache space.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: