rust - 为什么使用 Rust 将可变结构传递给函数会导致不可变字段?

标签 rust rust-0.8

我正在 Win8-64 上使用 0.8 学习 Rust。我有一个正在处理的测试程序,其中处理参数输入的函数返回包含这些参数的结构。那行得通。然后我修改了程序以将 &struct 传递给函数,现在我收到一个编译器错误,我正试图将其分配给一个不可变字段。

我应该如何将指针/引用传递给结构以防止出现此错误?

导致错误的代码(我尝试了一些变体):

let mut ocParams : cParams = cParams::new();     //!!!!!! This is the struct passed

fInputParams(&ocParams);               // !!!!!!! this is passing the struct

if !ocParams.tContinue {
    return;
}

.......

struct cParams {
  iInsertMax : i64,
  iUpdateMax : i64,
  iDeleteMax : i64,
  iInstanceMax : i64,
  tFirstInstance : bool,
  tCreateTables : bool,
  tContinue : bool
}

impl cParams {
  fn new() -> cParams {
     cParams {iInsertMax : -1, iUpdateMax : -1, iDeleteMax : -1, iInstanceMax : -1,
              tFirstInstance : false, tCreateTables : false, tContinue : false}
  }   
}

.....

fn fInputParams(mut ocParams : &cParams) {

    ocParams.tContinue = (sInput == ~"y");    // !!!!!! this is one of the error lines

函数中对结构字段的所有赋值都会导致编译时出错。编译导致的错误示例:

testli007.rs:240:2: 240:20 error: cannot assign to immutable field
testli007.rs:240   ocParams.tContinue = (sInput == ~"y");   

最佳答案

在你的函数声明中:

fn fInputParams(mut ocParams : &cParams) {

ocParams 是一个可变变量,包含一个指向不可变结构的借用指针。您想要的是该结构是可变的,而不是变量。因此,函数的签名应该是:

fn fInputParams(ocParams : &mut cParams) {

然后您必须将调用本身更改为 fInputParams:

fInputParams(&mut ocParams);  // pass a pointer to mutable struct.

关于rust - 为什么使用 Rust 将可变结构传递给函数会导致不可变字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19649005/

相关文章:

rust - 如何从 Rust 应用程序连接到 Docker 容器中的 SurrealDB?

rust - Rust:论点要求借用持续于 `' static`

rust - 当根据特征定义提取函数的返回类型时,如何提取 Rust 中的一部分函数?

function - 在闭包内调用堆上函数参数

arrays - 如何在 Rust 0.8 中将 Zip 转换为数组?

rust - 如何使用 Clap 提供多行帮助消息?

rust - 如何防止 Rust 程序 free()ing 不属于它的 C 字节

rust - 如何在 Rust 中读写文本文件?

sqlite - 可以在没有 "match"语句的情况下编写此 Rust 代码吗?