Menu
Coddy logo textTech

Modifying Arrays

Part of the Fundamentals section of Coddy's Rust journey — lesson 58 of 75.

In addition to accessing the elements of an array, you can also modify them. To modify a specific element, first you need mut to make an array modifiable, and then you can assign a new value to it using its index.

Here's an example:

let mut my_array = ["apple", "banana", "cherry"];
my_array[1] = "orange";
println!("{}, {}, {}", my_array[0], my_array[1], my_array[2]);

Output:

apple, orange, cherry

banana was changed to an orange.

challenge icon

Challenge

Easy

Create a program that receives 3 inputs:

  • First input is a string of values separated by a comma (for example 1,2,3,4,5) of length 5.
  • Second input is an index
  • Third input is a new element

The starter code already converts the comma-separated string into a mutable array called arr — you can work directly with it without writing any conversion code.

The program will print a modified array by changing the element at the index stored in the second input with the value from the third input.

Cheat sheet

To modify array elements, the array must be declared with mut:

let mut my_array = ["apple", "banana", "cherry"];
my_array[1] = "orange";
println!("{}, {}, {}", my_array[0], my_array[1], my_array[2]);

This changes the element at index 1 from "banana" to "orange".

Try it yourself

use std::io;
use std::convert::TryInto;

fn main() {
    let mut input_str_arr = String::new();
    let mut input_index = String::new();
    let mut new_element = String::new();
    io::stdin().read_line(&mut input_str_arr).unwrap();
    io::stdin().read_line(&mut input_index).unwrap();
    io::stdin().read_line(&mut new_element).unwrap();

    let new_element = new_element.trim().to_string();
    let index: usize = input_index.trim().parse().unwrap();
    let mut arr: [String; 5] = input_str_arr.split(',').map(String::from).collect::<Vec<String>>().try_into().unwrap();
    
    // Write your code below
    // Use arr, index and new_element to solve the challenge    

    for i in 0..arr.len() {
        print!("{} ", arr[i]);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals