[SOLVED] Iterating through array and changing it's values


#1

I have an array with 9 characters and I want to write the function which will take array as a parameter, loop through it and change all of it’s values to empty space. On basic level I understand how to do this;

let mut table: [ char; 9 ] = [ ' '; 9 ];
for field in &mut table {
    *field = ' ';
}

But when I have to write the actual function for this I completely screw up everything because I don’t quite understand references and borrowship. This is the only way in which compiler doesn’t return any error but of course it doesn’t work what I want;

fn clear_table(mut table: [ char; 9 ]) {
    for field in &mut table {
        *field = ' ';
    }
}

I would be grateful if someone can explain to me what should I do in this case.

P.S. I know I’m not really changing anything in the first example but I’ll fill the array in actual program so I need this.


#2

mut table: [ char; 9 ] means that you function receives value with type [ char; 9 ] (i.e. owned array, which gets moved when you call the function), which is bound to the mutable variable table. Having mutable variable allows you to mutate data in it, but note that if variable contains pointer you can change only this pointer, and not necessary data behind it. (e.g. let mut var = &foo; will not allow you to modify data in foo)

You want to pass mutable reference to your table instead,so your function will look like this:

fn clear_table(table: &mut [char; 9 ]) {
    for field in table {
        *field = ' ';
    }
}

This way your function can mutate data behind the pointer. BTW you also can change &mut [char; 9 ] to a more general &mut [char], arrays will get dereferenced to a slice automatically, so this code will work:

fn clear_table(table: &mut [char; 9 ]) { .. }
let mut table = ['a', 'b', 'c']; // table has type `[char; 3]`
clear_table(&mut table);

#3

Minor clarification: arrays are Copy if their element type is - this means calling clear_table copies the array, modifies the copy, but the original is left intact - I suspect that’s what was meant by “doesn’t work”.


#4

Thanks for clarification. Of course, it worked but it haven’t worked what I want :smiley: