Array Methods
Part of the Fundamentals section of Coddy's Rust journey — lesson 61 of 75.
Arrays are packed with many methods (functionalities). To access a method, write:
array.methodName(otherParameters)Here is a list of the basic methods:
len()- returns the number of elements in the arraycontains(value)- checks if the array contains a specific value
is_empty()- checks if the array is emptyreverse()- Reverses the array
For example:
let numbers = [10, 20, 30, 40, 50];
let length = numbers.len();
println!("Length: {}", length);
numbers.reverse()
// [50, 40, 30, 20, 10]Example of the is_empty() method:
let numbers: [i32; 0] = [];
let empty = numbers.is_empty();
println!("Is empty: {}", empty);This will output:
Is empty: trueWhen using contains, you need to pass a reference to the value you're looking for using &. For example:
let numbers = [10, 20, 30, 40, 50];
let has_thirty = numbers.contains(&30);
println!("Contains 30: {}", has_thirty);
// Output: Contains 30: trueChallenge
EasyCreate a function named analyze_array that receives an array of strings of size 5 as an argument. The method should perform the following operations:
- Check if the array is empty using the
is_empty()method and print the result. - Check if the array contains the string
“5”using thecontains()method and print the result. Remember to use String and not str:“5”.to_string() - Reverse the array and print it
The output should follow this exact format:
Is empty: [true or false]
Contains 5: [true or false]
Reversed Elements:
[element1]
[element2]
...Cheat sheet
Arrays have built-in methods accessed with dot notation:
array.methodName(otherParameters)Basic array methods:
len()- returns the number of elementscontains(value)- checks if array contains a specific valueis_empty()- checks if array is emptyreverse()- reverses the array
Examples:
let numbers = [10, 20, 30, 40, 50];
let length = numbers.len();
let has_thirty = numbers.contains(&30);
let empty = numbers.is_empty();
numbers.reverse(); // [50, 40, 30, 20, 10]Note: contains() requires a reference to the value using &.
Try it yourself
use std::io;
use std::convert::TryInto;
fn analyze_array(arr: &mut [String; 5]) {
// Write code here
// Print elements line by line
for element in arr.iter() {
println!("{}", element);
}
}
fn main() {
let mut input_str_arr = String::new();
io::stdin().read_line(&mut input_str_arr).unwrap();
let mut arr: [String; 5] = input_str_arr.split(',').map(String::from).collect::<Vec<String>>().try_into().unwrap();
analyze_array(&mut arr);
}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 Comparison13Arrays Continued
Mutable Reference ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayBetter Print5Operators 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 Input