When should I use a reference instead of transferring ownership?

自闭症网瘾萝莉.ら 提交于 2019-12-10 18:03:28

问题


From the Rust book's chapter on ownership, non-copyable values can be passed to functions by either transferring ownership or by using a mutable or immutable reference. When you transfer ownership of a value, it can't be used in the original function anymore: you must return it back if you want to. When you pass a reference, you borrow the value and can still use it.

I come from languages where values are immutable by default (Haskell, Idris and the like). As such, I'd probably never think about using references at all. Having the same value in two places looks dangerous (or, at least, awkward) to me. Since references are a feature, there must be a reason to use them.

Are there situations I should force myself to use references? What are those situations and why are they beneficial? Or are they just for convenience and defaulting to passing ownership is fine?


回答1:


Mutable references in particular look very dangerous.

They are not dangerous, because the Rust compiler will not let you do anything dangerous. If you have a &mut reference to a value then you cannot simultaneously have any other references to it.

In general you should pass references around. This saves copying memory and should be the default thing you do, unless you have a good reason to do otherwise.

Some good reasons to transfer ownership instead:

  1. When the value's type is small in size, such as bool, u32, etc. It's often better performance to move/copy these values to avoid a level of indirection. Usually these values implement Copy, and actually the compiler may make this optimisation for you automatically. Something it's free to do because of a strong type system and immutability by default!
  2. When the value's current owner is going to go out of scope, you may want to move the value somewhere else to keep it alive.


来源:https://stackoverflow.com/questions/50027822/when-should-i-use-a-reference-instead-of-transferring-ownership

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!