Reputation: 10720
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");
Upvotes: 8
Views: 7050
Reputation: 15538
In the declaration of your function:
fn fInputParams(mut ocParams : &cParams) {
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) {
Then you have to change the call itself to fInputParams
:
fInputParams(&mut ocParams); // pass a pointer to mutable struct.
Upvotes: 17