Menu
CoddyTech

Vectors and Iteration

Lesson 14 of 48 in Coddy's Rust for C Developers course.

A Rust Vec<T> owns a growable contiguous allocation. In C, the equivalent needs a pointer plus length and capacity, with allocation and cleanup handled separately. Vec::new() creates an empty vector, push appends an element, and len reports the current element count. Capacity is reserved storage, not the number of initialized elements. Do not index spare capacity as if it were part of the vector. pop removes the last element and returns Some(value), or None if empty; match can handle both cases. for &value in &items borrows a vector and copies each integer into the loop binding. Returning a vector transfers its ownership to the caller; its allocation is released automatically when its owner is dropped. The task returns a new vector, so the borrowed input remains available after the call.

C

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    int *items = malloc(2 * sizeof *items);
    if (items == NULL) return 1;
    size_t length = 0;
    items[length++] = 3; items[length++] = 8;
    int removed = items[--length];
    printf("removed=%d size=%zu\n", removed, length);
    for (size_t i = 0; i < length; ++i) printf("%d\n", items[i]);
    free(items);
    return 0;
}

Rust

fn main() {
    let mut items = Vec::new();
    items.push(3);
    items.push(8);
    match items.pop() {
        Some(removed) => println!("removed={} size={}", removed, items.len()),
        None => println!("empty"),
    }
    for &value in &items { println!("{}", value); }
}

A vector may reallocate when it grows. Rust prevents holding a borrowed element across a conflicting push; do not port C dangling-pointer habits.

challenge icon

Challenge

Easy

Compress consecutive repeated readings. Input is zero to thirty whitespace-separated integers between -100 and 100. Required API: pub fn compress(values: &[i32]) -> Vec<i32> returns a new vector retaining the first value of each consecutive run. Nonadjacent equal values remain separate: 4 4 2 4 becomes 4 2 4. Preserve order and leave the input unchanged. Empty input returns an empty vector. Output retained integers separated by one space, or empty when there are none. Implement the public API in runs.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, runs.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod runs;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
let data = [8, 8, -2, -2, 8, 1, 1];
assert_eq!(runs::compress(&data), vec![8, -2, 8, 1]);
assert_eq!(runs::compress(&[]), Vec::<i32>::new());
assert_eq!(runs::compress(&[6]), vec![6]);
assert_eq!(runs::compress(&[3, 3, 3]), vec![3]);
assert_eq!(runs::compress(&data[1..6]), vec![8, -2, 8, 1]);
assert_eq!(data, [8, 8, -2, -2, 8, 1, 1]);
assert_eq!(runs::compress(&data), vec![8, -2, 8, 1]);
    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for C Developers

Practice on your own: Online Rust compiler