Removing Elements
Part of the Logic & Flow section of Coddy's Rust journey — lesson 13 of 66.
Sometimes you need to remove elements from a vector, not just add them. Rust provides two main methods for removing elements, each designed for different situations.
The .pop() method removes and returns the last element from the vector:
let mut numbers = vec![10, 20, 30, 40];
let last = numbers.pop(); // removes 40, returns Some(40)
// numbers is now [10, 20, 30]Notice that .pop() returns an Option - it gives you Some(value) if there was an element to remove, or None if the vector was already empty. This makes it safe to use even on empty vectors.
The .remove() method removes an element at a specific index and returns that element:
let mut fruits = vec!["apple", "banana", "cherry"];
let removed = fruits.remove(1); // removes "banana"
// fruits is now ["apple", "cherry"]When you use .remove(), all elements after the removed index shift left to fill the gap. This operation can be slower for large vectors when removing from the beginning or middle, since many elements need to be moved.
Both methods require the vector to be mutable since they modify its contents. Choose .pop() when you want to remove from the end, and .remove() when you need to remove from a specific position.
Challenge
EasyYou will receive two inputs: first, a comma-separated list of numbers, and second, an index to remove. Read both inputs, create a vector from the numbers, remove the element at the specified index, and print the remaining elements on separate lines.
Requirements:
- Read the first input containing comma-separated numbers (e.g.,
10,20,30,40,50) - Split the string by commas and convert each number to an integer
- Create a mutable vector from these numbers
- Read the second input and convert it to an integer representing the index
- Use
.remove()to remove the element at that index - Print each remaining element on a separate line
Input:
- First line: Comma-separated integers (e.g.,
10,20,30,40,50) - Second line: An integer representing the index to remove
Output: Print each remaining element of the vector on a separate line
Cheat sheet
Rust provides two main methods for removing elements from vectors:
The .pop() method removes and returns the last element:
let mut numbers = vec![10, 20, 30, 40];
let last = numbers.pop(); // removes 40, returns Some(40)
// numbers is now [10, 20, 30].pop() returns an Option type - Some(value) if an element was removed, or None if the vector was empty.
The .remove() method removes an element at a specific index and returns it:
let mut fruits = vec!["apple", "banana", "cherry"];
let removed = fruits.remove(1); // removes "banana"
// fruits is now ["apple", "cherry"]When using .remove(), all elements after the removed index shift left to fill the gap.
Both methods require the vector to be mutable. Use .pop() for removing from the end, and .remove() for removing from a specific position.
Try it yourself
use std::io;
fn main() {
// Read the comma-separated numbers
let mut numbers_input = String::new();
io::stdin().read_line(&mut numbers_input).expect("Failed to read line");
// Read the index to remove
let mut index_input = String::new();
io::stdin().read_line(&mut index_input).expect("Failed to read line");
// TODO: Write your code below
// 1. Split the numbers_input by commas and convert to integers
// 2. Create a mutable vector from these numbers
// 3. Convert index_input to an integer
// 4. Remove the element at the specified index
// 5. Print each remaining element on a separate line
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 together