Pybites Logo Rust Platform

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:

  1. sum_slice(v: &[i32]) -> i32
    Return the sum of all elements.

  2. square_in_place(v: &mut [i32])
    Modify the slice in-place, squaring each element.


💡 Hints

  • Use .iter() for reading and a simple for x in v { *x *= *x; } for mutation.
  • An empty slice (summing []) should yield 0.

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);