Vectors and Vec
Level: intro (score: 1)
🎯 In Python, lists are dynamic arrays.
In Rust, Vec<T>
is the growable list type — but idiomatic function signatures often accept slices so they work with both Vec<T>
and arrays.
Key points for Pythonistas:
- Prefer
&[T]
for read-only access and&mut [T]
for in-place mutation. - You can pass a whole vector as a slice with
&v[..]
(read) or&mut v[..]
(write).
✅ Your task (slice-based)
Implement two functions:
-
sum_slice(v: &[i32]) -> i32
Return the sum of all elements. -
square_in_place(v: &mut [i32])
Modify the slice in-place, squaring each element.
💡 Hints
- Use
.iter()
for reading and a simplefor x in v { *x *= *x; }
for mutation. - An empty slice (summing
[]
) should yield0
.
Example tests:
let mut nums = vec![1, 2, 3];
square_in_place(&mut nums[..]);
assert_eq!(nums, vec![1, 4, 9]);
assert_eq!(sum_slice(&nums[..]), 14);
assert_eq!(sum_slice(&[]), 0);