Other Slices
Part of the Logic & Flow section of Coddy's Rust journey — lesson 57 of 66.
While string slices are very useful, slicing isn't limited to just strings. Rust's slice concept extends to any sequence of elements, making it a powerful tool for working with collections without taking ownership.
You can create slices from arrays and vectors using the same syntax you learned for strings. For example, if you have an array of numbers, you can create a slice that references part or all of it:
let numbers = [1, 2, 3, 4, 5];
let slice: &[i32] = &numbers[1..4]; // This gives us [2, 3, 4]
let full_slice: &[i32] = &numbers; // This references the entire arrayThe same principle works with vectors. You can create slices from vectors to work with portions of the data without moving or copying it:
let mut vec = vec![10, 20, 30, 40];
let vec_slice: &[i32] = &vec[0..2]; // This gives us [10, 20]Challenge
EasyYou will receive three inputs. The first input is a comma-separated list of numbers. The second input is two numbers separated by a space representing the start and end indices for creating a slice. The third input is a single number representing an index to access from the slice.
Create a vector from the comma-separated numbers, then create a slice using the specified range. Access the element at the given index from the slice and print it.
Requirements:
- Read the first input (comma-separated numbers) and trim whitespace
- Split the input by commas and parse each number to
i32 - Create a vector from these numbers
- Read the second input (two numbers separated by a space) and trim whitespace
- Split the second input by space to get the start and end indices
- Parse both indices to
usize - Create a slice from the vector using the range syntax
&vec[start..end] - Read the third input (index to access) and trim whitespace
- Parse the index to
usize - Access the element at the specified index from the slice
- Print the accessed element
Input:
- First line: Comma-separated numbers (e.g.,
10,20,30,40,50) - Second line: Two numbers separated by a space (e.g.,
1 4) - Third line: An index number (e.g.,
2)
Output:
- The element at the specified index from the slice
Cheat sheet
Slices can be created from arrays and vectors, not just strings. They reference a portion of a collection without taking ownership.
Creating slices from arrays:
let numbers = [1, 2, 3, 4, 5];
let slice: &[i32] = &numbers[1..4]; // References [2, 3, 4]
let full_slice: &[i32] = &numbers; // References the entire arrayCreating slices from vectors:
let mut vec = vec![10, 20, 30, 40];
let vec_slice: &[i32] = &vec[0..2]; // References [10, 20]Slices use the same range syntax as string slices and allow you to work with portions of data without moving or copying it.
Try it yourself
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
// Read the first input (comma-separated numbers)
let first_input = lines.next().unwrap().unwrap();
// Read the second input (start and end indices)
let second_input = lines.next().unwrap().unwrap();
// Read the third input (index to access)
let third_input = lines.next().unwrap().unwrap();
// TODO: Write your code below
// Parse the comma-separated numbers and create a vector
// Parse the start and end indices
// Create a slice from the vector
// Access the element at the specified index from the slice
// Print the result
// println!("{}", result);
}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 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 Element9String Slices and More
String vs. &strCreating String SlicesSlices as Function ParametersOther SlicesRecap - Find First Word