Menu
CoddyTech

Vectors and Iteration

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

A JavaScript array grows with push and shrinks with pop, and declaring it with const stops neither, because const fixes the variable, not the array's contents. Its elements may mix types. When the array is empty, pop returns undefined, which looks the same as a stored undefined element. A Rust Vec<T> owns a growable sequence of one element type. The vec! macro builds one with initial elements, and Vec::new() starts an empty one. Changing it with push or pop requires a let mut binding. pop returns Option<T>: Some(value) while elements remain and None afterwards, so an empty vector cannot be confused with a stored value. The method last() peeks at the final element the same way without removing it. The loop for step in &route borrows each element and leaves the vector usable; for step in route would consume the vector. While a borrowed element is still in use, the compiler forbids pushing, because growing can move the storage. The {:?} format prints the Option values.

Complete standalone JavaScript program:

const route = ["north"];
route.push("south");
for (const step of route) {
  console.log(step);
}
console.log(route.pop());
console.log(route.pop());
console.log(route.pop());

JavaScript output:

north
south
south
north
undefined

Complete standalone Rust program:

fn main() {
    let mut route = vec!["north".to_string()];
    route.push("south".to_string());
    for step in &route {
        println!("{}", step);
    }
    println!("{:?}", route.pop());
    println!("{:?}", route.pop());
    println!("{:?}", route.pop());
}

Rust output:

north
south
Some("south")
Some("north")
None
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 JavaScript Developers

Practice on your own: Online Rust compiler