为什么在Rust中将可变结构体传递给函数会导致不可变字段?

7
我正在使用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");   
1个回答

16
在您的函数声明中:
fn fInputParams(mut ocParams : &cParams) {

ocParams 是一个可变变量,包含对不可变结构体的借用指针。你需要的是让这个结构体可变,而不是让变量可变。因此,函数的签名应该是:

fn fInputParams(ocParams : &mut cParams) {

然后你需要将调用本身更改为fInputParams

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

非常感谢,我会勾选它的。 - Brian Oh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接