## DEV Community is a community of 640,432 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Mutable Arrays in Rust Anil Kumar Khandei
Fullstack Development, Azure, Serverless, React, JS, MVC, API, Razor Pages, Donetcore
・2 min read

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,9,10,3,5};
//that simple
foreach(int i in m_h)
{
m_h[i] += 1; //increment each element of the array by 1
}
``````

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??
}
``````

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
}
``````

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]);
}
``````

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