简体   繁体   English

为什么将结构传递给 Rust 中的 function 将其永久移动到该 function?

[英]Why does passing a struct to a function in Rust permanently move it to that function?

Example:例子:

let mut protagonist = Vec::new(); 
for (_i, _c) in challenger.chars().enumerate() {   
    protagonist.push('_');
}
let s = String::from_iter(protagonist);

protagonist.push('t'); // error: value borrowed here after move

I know that in order to solve it you have to write &protagonist instead when passing it to the from_iter() function.我知道为了解决它,你必须在将它传递给from_iter() function 时编写&protagonist protagonist。 As in pass by reference, instead of value.正如通过引用传递,而不是值传递。 But my question is why does the object move away in the first place when you pass by value and you can no longer use it anymore in your main function?但我的问题是,为什么 object 在您传递值时首先会移开,并且您不能再在主 function 中使用它? What purpose does this serve?这是为了什么目的?

This behavior is part of Rust's core feature of ownership and borrowing , which is the mechanic that provides Rust's memory safety guarantees.这种行为是 Rust 的所有权和借用核心特性的一部分,这是提供 Rust 的 memory 安全保证的机制。

It's purpose is to ensure memory management without requiring GC.其目的是确保 memory 管理不需要 GC。 The model Rust uses is Ownership-based, so all objects can have one owner only. model Rust 使用的是基于所有权的,因此所有对象只能有一个所有者。 Now, there are 3 ways of using a variable based on this, either you give up ownership of the variable, let the variable be borrowed immutably or let it be mutable borrowed.现在,基于此,有 3 种使用变量的方法,要么放弃变量的所有权,让变量不可变地借用,要么可变地借用。 It is to ensure proper memory management based on need.这是为了确保根据需要进行适当的 memory 管理。 If you know you will not use the variable again, you can transfer its ownership and the old value gets dropped.如果您知道不会再次使用该变量,则可以转移其所有权,旧值将被删除。 If you know you will use the variable, you can borrow it (mutably or immutably, based on your need).如果您知道将使用该变量,则可以借用它(根据您的需要可变或不可变地借用)。 So, you won't be having unused variables and it makes you thin =k about memory management properly, helping you fix some problems that might occur later.因此,您不会有未使用的变量,它会让您对 memory 的正确管理变得更加细心,帮助您解决以后可能出现的一些问题。

In your example, your code indicates to the compiler that you don't want to use the variable anymore in the main function, this is by the design of the language itself.在您的示例中,您的代码向编译器表明您不想再在主 function 中使用该变量,这是语言本身的设计。 Remember, the compiler can perform 3 different things (move, borrow and mutable borrow), hence the programmer is expected to let the compiler know which option they are choosing.请记住,编译器可以执行 3 种不同的操作(移动、借用和可变借用),因此程序员应该让编译器知道他们正在选择哪个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM