为什么使用Rust会将可变结构传递给不可变字段中的函数结果?

Bri*_* Oh 4 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
Run Code Online (Sandbox Code Playgroud)

函数中struct结构字段的所有赋值都会在编译时导致错误.编译产生的错误示例:

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

Cyr*_* Ka 11

在你的功能声明中:

fn fInputParams(mut ocParams : &cParams) {
Run Code Online (Sandbox Code Playgroud)

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

fn fInputParams(ocParams : &mut cParams) {
Run Code Online (Sandbox Code Playgroud)

然后你必须将呼叫本身更改为fInputParams:

fInputParams(&mut ocParams);  // pass a pointer to mutable struct.
Run Code Online (Sandbox Code Playgroud)