Reverse a String
🎯 In Python, reversing a string is a one-liner: s[::-1]. Rust doesn't have slicing syntax like that, but it has something arguably more powerful: iterator adapters.
You already know .chars() gives you an iterator over characters. Rust iterators have a rich set of adapter methods that transform the sequence without consuming it:
let nums = vec![1, 2, 3, 4, 5];
let first_three: Vec<i32> = nums.iter()
.take(3)
.copied()
.collect();
// [1, 2, 3]
Notice .collect() at the end — this is a key Rust concept. Iterators are lazy: adapter methods like .take(), .map(), and .filter() just build up a chain of transformations. Nothing actually happens until you consume the iterator. .collect() is the most common consumer — it gathers results into a collection.
The magic: .collect() figures out what type to build from the return type. It can produce a Vec<T>, a String, a HashSet<T>, and more — all from the same method call. The compiler uses the expected type to decide:
let v: Vec<char> = "hello".chars().collect(); // Vec of chars
let s: String = "hello".chars().collect(); // back to a String
Explore the iterator docs — there are adapters for skipping, filtering, transforming, reversing, and much more. Browsing the Iterator trait methods is a great way to discover what's available.
Login to see the full task and start coding.
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise