recursion - Rust: passing array recursively -


i got started rust , have mixed feelings. take dummy example, hope self-explanatory:

fn set_values(pos: usize, val: u64, array: &mut [u64]) {     if pos >= array.len() {         return;     }     array[pos] = val;     set_values(pos+1, val+1, array); } 

this works fine calling:

set_values(0, 42, &mut my_array); 

i totally reason behind &mut in first function call, why hell during recursive call don't have specify it?

not that, if decide write set_values(pos+1, val+1, &mut array); compiler complains , tells me have change function signature to

fn set_values(pos: usize, val: u64, mut array: &mut [u64]) 

sorry me doesn't make sense.

when declaring array, you're doing

let myarray = vec::new(); 

to call as,

set_values(0, 42, &mut my_array); 

in above statement, you're making mutable reference out of array. because function expects mutable reference array, types have match. simple enough?

within function type of array known &mut [u64]

so don't need make mutable reference out of since it's mutable reference. :).


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -