Pybites Logo Rust Platform

Vec Operations

Medium +3 pts

In Python, lists are your go-to collection:

items = [1, 2, 3]
items.append(4)
items.extend([5, 6])
first = items.pop(0)
items.insert(0, first)

Rust's Vec<T> is similar but with explicit types and ownership semantics.

Creating vectors

let mut v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3];  // macro for convenience

Adding elements

let mut v = vec![1, 2, 3];
v.push(4);              // add to end
v.extend([5, 6]);       // add multiple
v.insert(0, 0);         // insert at index

Removing elements

let last = v.pop();           // Option<T> - might be empty
let removed = v.remove(0);    // panics if out of bounds
v.retain(|&x| x > 2);         // keep only matching elements

Accessing elements

let first = v[0];             // panics if empty
let first = v.get(0);         // Option<&T> - safe
let first = v.first();        // Option<&T>
let last = v.last();          // Option<&T>

Slices: borrowed views

let slice: &[i32] = &v[1..3];  // borrow a portion
let all: &[i32] = &v;          // borrow entire vec

Functions that don't need ownership should take &[T] (slice) instead of &Vec<T> - more flexible.


Your Task

  1. merge_sorted(a: &[i32], b: &[i32]) -> Vec<i32> — merge two already-sorted slices into one sorted Vec
  2. chunk_vec(items: Vec<i32>, size: usize) -> Vec<Vec<i32>> — …

Login to see the full exercise.