mirror of
https://github.com/rust-lang/rustlings.git
synced 2026-01-12 05:39:19 +00:00
Some more reading required on the following: - `move_semantics` aka ownership and borrowing. - `enums` especially using with match expressions.
45 lines
1.1 KiB
Rust
45 lines
1.1 KiB
Rust
// vecs2.rs
|
|
// A Vec of even numbers is given. Your task is to complete the loop
|
|
// so that each number in the Vec is multiplied by 2.
|
|
//
|
|
// Make me pass the test!
|
|
//
|
|
// Execute `rustlings hint vecs2` or use the `hint` watch subcommand for a hint.
|
|
|
|
fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
|
|
for i in v.iter_mut() {
|
|
// Fill this up so that each element `i` in Vec `v` is multiplied by 2.
|
|
*i *= 2;
|
|
}
|
|
|
|
return v;
|
|
}
|
|
|
|
fn vec_map(v: &Vec<i32>) -> Vec<i32> {
|
|
v.iter().map(|num| {
|
|
// Instead of mutating the Vec as above, we can just return the new number!
|
|
return num * 2;
|
|
}).collect()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_vec_loop() {
|
|
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
|
|
let ans = vec_loop(v.clone());
|
|
|
|
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
|
|
}
|
|
|
|
#[test]
|
|
fn test_vec_map() {
|
|
let v: Vec<i32> = (1..).filter(|x| x % 2 == 0).take(5).collect();
|
|
let ans = vec_map(&v);
|
|
|
|
assert_eq!(ans, v.iter().map(|x| x * 2).collect::<Vec<i32>>());
|
|
}
|
|
}
|