为什么使用 Rust 将可变结构传递给函数会导致不可变字段? [英] Why using Rust does passing a mutable struct to a function result in immutable fields?
问题描述
我正在 Win8-64 上使用 0.8 学习 Rust.我有一个测试程序,我正在处理一个处理参数输入的函数返回一个包含这些参数的结构.那工作正常.然后我修改了程序以将 &struct 传递给函数,现在我得到一个编译器错误,我试图将它分配给一个不可变字段.
I'm learning Rust using 0.8 on Win8-64. I have a test program I'm working on where a function that handles input of parameters returned a struct containing those parameters. That worked OK. I then altered the program to pass the &struct to the function, and I now get a compiler error that I'm attempting to assign to an immutable field.
我应该如何将指针/引用传递给结构以防止出现此错误?
How should I be passing a pointer/reference to the struct to prevent this error?
导致错误的代码(我尝试了一些变体):
The code that results in the error (I've tried a few variations) :
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
对函数中结构域的所有赋值都会导致编译时出错.编译导致的错误示例:
All of the assignments to the struct fields in the function result in an error at compile-time. An example of the errors that result from compile :
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
是一个可变变量,包含一个借用的指向不可变结构的指针.您想要的是该结构是可变的,而不是变量.因此,函数的签名应该是:
ocParams
is a mutable variable containing a borrowed pointer to an immutable struct. What you want is for that struct to be mutable, not the variable. Therefore, the signature of the function should be:
fn fInputParams(ocParams : &mut cParams) {
然后您必须将调用本身更改为fInputParams
:
Then you have to change the call itself to fInputParams
:
fInputParams(&mut ocParams); // pass a pointer to mutable struct.
这篇关于为什么使用 Rust 将可变结构传递给函数会导致不可变字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!