Search code examples
rustvector

Rust Iterate through a vector of string and mutate the contents


I am a newbie in Rust. I want to iterate through a vector of String and modify the values. How will one do it? Below is the code I wrote, but it fails.

let mut val: [&str; 3] = ["Hello", "Hi", "Hey"];
for value in val.iter_mut() {
    *value = *value + "a";
    println!("{}", value);
}

Say I just want to add the letter "a" to each of the elements in val.


Solution

  • fn main() {
        let mut val: [String; 3] = ["Hello".to_string(), "Hi".to_string(), "Hey".to_string()];
        val.iter_mut().for_each(|s| s.push('a'));
        println!("{val:#?}");
    }