【问题标题】:Why using Rust does passing a mutable struct to a function result in immutable fields?为什么使用 Rust 将可变结构传递给函数会导致不可变字段?
【发布时间】:2013-10-29 03:15:07
【问题描述】:

我在 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");   

【问题讨论】:

    标签: rust rust-0.8


    【解决方案1】:

    在你的函数声明中:

    fn fInputParams(mut ocParams : &cParams) {
    

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

    fn fInputParams(ocParams : &mut cParams) {
    

    那你得把调用本身改成fInputParams

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

    【讨论】:

    • 非常感谢,我会勾选的。
    猜你喜欢
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2015-02-12
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多