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, cherrybanana was changed to an orange.
Challenge
EasyCreate 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.
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]);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input12Arrays Basics
Declaring ArraysArray as ParameterAccessing ElementsModifying ArraysRecap - Pretty Print Array