Recap - Find an Element
Part of the Logic & Flow section of Coddy's Rust journey — lesson 41 of 66.
Challenge
EasyYou will receive two inputs. The first input is a list of numbers separated by commas (e.g., 10,20,30,40), and the second input is a target number to search for. Parse the comma-separated numbers into a vector, then search for the target number. Use .iter().position() to find the index of the target number, which returns an Option<usize>. Handle both cases using match and print the appropriate message.
Requirements:
- Read the first input (comma-separated numbers) and trim whitespace
- Split the input by commas and parse each part into
i32to create a vector - Read the second input (target number) and trim whitespace
- Parse the target number to
i32 - Use
.iter().position(|&x| x == target)to search for the target in the vector - Use a
matchexpression to handle theOptionreturned by.position() - In the
Some(index)arm, print:Found at index [index] - In the
Nonearm, print:Not found
Input:
- First line: Comma-separated numbers (e.g.,
10,20,30,40) - Second line: A target number to search for (e.g.,
30)
Output:
- If the target is found:
Found at index [index] - If the target is not found:
Not found
Try it yourself
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
// Read the comma-separated numbers
let numbers_input = lines.next().unwrap().unwrap().trim().to_string();
// Read the target number
let target_input = lines.next().unwrap().unwrap().trim().to_string();
// Parse the comma-separated numbers into a vector
let numbers: Vec<i32> = numbers_input
.split(',')
.map(|s| s.trim().parse().unwrap())
.collect();
// Parse the target number
let target: i32 = target_input.parse().unwrap();
// TODO: Write your code below
// Use .iter().position() to find the target and match to handle the result
}All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together6Handling Absence with 'Option'
What is an 'Option'?Using 'match' with 'Option'is_some() and is_none()Unwrapping an 'Option'The expectProviding a Default: unwrap_orRecap - Find an Element