DEV Community

Anil Kumar Khandei
Anil Kumar Khandei

Posted on

Mutable Arrays in Rust

I want to discuss briefly about mutable arrays in rust and how i learnt it the hard way. I come from a C# background so creating an array of integers, iterating over the array and changing the values is a cake walk.

In C#-

    int[] m_h = { 9,5,1,8,2};//or
    int[] m_h_new = new int[5] { 5,9,10,3,5};
    //that simple
    foreach(int i in m_h)
    {
        m_h[i] += 1; //increment each element of the array by 1
    }
Enter fullscreen mode Exit fullscreen mode

However it is not the same in rust, even though it is simple, it took sometime for me to understand the concepts.

Then I tried something similar in rust-

//create a mutable array of 5 elements
    let mut m_h:[i32;5]=[9,3,2,8,1];
    //now since I set it mutable i guess this should work...
    //enumerate() returns a tuple with the (index, value) of each element of the array
    for (i,h) in m_h.iter().enumerate(){
        //however this fails
        m_h[i]=h+1;//cannot assign to m_h[_] as it is borrowed
        //well what i cant understand is if i made it mutable why cant i change it??
    }
Enter fullscreen mode Exit fullscreen mode

I did some googling and found that iter() returns a reference where as iter_mut() returns a mutable reference.

Therefore the correct way to iterate an array and modify its contents is-

//create a mutable array of 5 elements
    let mut m_h:[i32;5]=[9,3,2,8,1];
    for (i,h) in m_h.iter_mut().enumerate(){
        //m_h[i]=h+1; this syntax wont work here :)
        //wait hold on what & why?? i cant do this too??
        //well of course iter_mut returns a reference so inorder to modify it we need to dereference it like so
        *h=*h+1;//this is the correct syntax here
    }
Enter fullscreen mode Exit fullscreen mode

Also the most straight forward way to iterate an array and modify context is just using a range instead of iter() or iter_mut()-

Like so-

for i in 0..m_h.len(){
    m_h[i]=m_h[i]+1;
    println!("{}",m_h[i]);
}
Enter fullscreen mode Exit fullscreen mode

Simple isn't. I hope it was worth the read and hope it was helpful!

Top comments (2)

Collapse
 
geoxion profile image
Dion Dokter

You should prefer the iterator. You're less likely to screw up and the compiler knows your intention better (thus it's possible for it to generate better code).
But it's good you're trying out Rust. I've found it to be a really cool language!

Collapse
 
anilkhandei profile image
Anil Kumar Khandei

Yeah makes sense will do thanks for the direction.