Adding Elements with push
Part of the Logic & Flow section of Coddy's Rust journey — lesson 9 of 66.
Once you have a vector, you'll often want to add new elements to it. Rust provides the .push() method to add elements to the end of a vector. This is one of the most common operations you'll perform with vectors.
Here's how to use .push():
let mut numbers = Vec::new();
numbers.push(10);
numbers.push(20);
numbers.push(30);Notice the mut keyword - this is crucial! Since adding elements changes the vector's contents, the vector must be declared as mutable. Without mut, Rust won't allow you to modify the vector.
The .push() method always adds the new element to the end of the vector. Each call to .push() increases the vector's length by one:
let mut fruits = Vec::new();
fruits.push("apple");
fruits.push("banana");
// fruits now contains ["apple", "banana"]You can also start with a vector that already has elements and continue adding to it:
let mut scores = vec![85, 92];
scores.push(78); // scores is now [85, 92, 78]Challenge
EasyYou will receive three numbers as input, each on a separate line. Read these numbers, convert them to integers, and add them to a vector using the .push() method. After adding all three numbers, print each element of the vector on a separate line.
Requirements:
- Create an empty mutable vector
- Read three numbers from input and convert each to an integer
- Use
.push()to add each number to the vector - Print each element of the vector on a separate line
Input: Three integers, each on a separate line
Output: Print each element of the vector on a separate line
Cheat sheet
To add elements to a vector, use the .push() method. The vector must be declared as mutable with the mut keyword:
let mut numbers = Vec::new();
numbers.push(10);
numbers.push(20);
numbers.push(30);The .push() method adds elements to the end of the vector and increases its length by one with each call.
You can also add elements to a vector that already contains values:
let mut scores = vec![85, 92];
scores.push(78); // scores is now [85, 92, 78]Try it yourself
use std::io;
fn main() {
// Read three numbers from input
let mut input1 = String::new();
io::stdin().read_line(&mut input1).expect("Failed to read line");
let num1: i32 = input1.trim().parse().expect("Invalid input");
let mut input2 = String::new();
io::stdin().read_line(&mut input2).expect("Failed to read line");
let num2: i32 = input2.trim().parse().expect("Invalid input");
let mut input3 = String::new();
io::stdin().read_line(&mut input3).expect("Failed to read line");
let num3: i32 = input3.trim().parse().expect("Invalid input");
// TODO: Write your code below
// Create a mutable vector and push the numbers to it
// Print each element of the vector 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