什么时候应该使用引用而不是所有权转移? [英] When should I use a reference instead of transferring ownership?

查看:97
本文介绍了什么时候应该使用引用而不是所有权转移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Rust书中有关所有权的章节,可以通过转移所有权或使用可变或不可变的引用将不可复制的值传递给函数.当您转移值的所有权时,该值不能再在原始函数中使用:如果需要,必须将其返回.传递引用时,您可以借用该值,并且仍可以使用它.

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.

我来自默认情况下值是不可变的语言(Haskell,Idris等).因此,我可能根本不会考虑使用引用.在两个地方具有相同的值对我来说似乎很危险(或者至少很尴尬).由于引用是一项功能,因此必须有使用它们的理由.

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?

推荐答案

尤其是可变引用看起来非常危险.

Mutable references in particular look very dangerous.

它们并不危险,因为Rust编译器不会让您做任何危险的事情.如果您有对值的&mut引用,则不能同时具有任何对该值的引用.

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.

general 中,您应该传递引用.这样可以节省复制内存,并且应该将其作为默认操作,除非您有充分的理由这样做.

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. 当值的类型较小时,例如boolu32等.移动/复制这些值以避免一定程度的间接访问通常会获得更好的性能.通常,这些值实现Copy,实际上,编译器可能会自动为您进行此优化.由于强大的类型系统和默认情况下的不可变性,因此可以免费执行某些操作!
  2. 当值的当前所有者将超出范围时,您可能需要将值移动到其他位置以使其保持活动状态.
  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.

这篇关于什么时候应该使用引用而不是所有权转移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆