且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不能将不可变变量作为参数传递给需要可变参数的函数?

更新时间:2021-08-29 21:29:22

按值传递时,您正在转让值的所有权.不需要变量的副本-首先main拥有它,然后reset拥有它,然后消失了 1 .

When you pass by value, you are transferring ownership of the value. No copies of the variable are required — first main owns it, then reset owns it, then it's gone1.

在Rust中,当您拥有一个变量的所有权时,您可以控制它的可变性.例如,您可以执行以下操作:

In Rust, when you have ownership of a variable, you can control the mutability of it. For example, you can do this:

let a = [1, 2, 3, 4, 5];
let mut b = a;

您也可以在reset内部执行相同的操作,尽管我不会 执行此操作,而是希望在函数签名中使用mut:

You could also do the same thing inside of reset, although I would not do this, preferring to use the mut in the function signature:

fn reset(b: [u32; 5]) {
    let mut c = b;
    c[0] = 5;
}

另请参阅:

  • What's the idiomatic way to pass by mutable value?
  • What's the difference between placing "mut" before a variable name and after the ":"?

1 —在此特定情况下,您的类型是[i32; 5],它实现了Copy特性.如果您在授予reset所有权后尝试使用a,则将创建一个隐式副本. a的值将保持不变.

1 — In this specific case, your type is an [i32; 5], which implements the Copy trait. If you attempted to use a after giving ownership to reset, then an implicit copy would be made. The value of a would appear unchanged.