Vectors and Iteration
Lesson 14 of 48 in Coddy's Rust for Java Developers course.
Java ArrayList<Integer> stores boxed integer references and grows as needed. Rust Vec<i32> owns a growable contiguous buffer of integers. Its length and capacity are different: length counts initialized elements, while capacity describes available allocation space. push appends an element and pop removes the last element, returning None when empty.
Rust iteration chooses an ownership mode. for x in &values borrows elements, for x in &mut values permits element mutation, and consuming a vector by value transfers its elements into the iterator. These modes are not interchangeable with Java's ordinary object aliasing. A growth operation can reallocate a vector, so Rust rejects keeping a usable element reference across a conflicting mutation such as a push.
Java: complete program
class Main {
public static void main(String[] args) {
java.util.ArrayList<Integer> a = new java.util.ArrayList<>();
a.add(4); a.add(8);
int last = a.remove(a.size() - 1);
System.out.println(last + ":" + a.size());
}
}Rust: complete program
fn main() {
let mut a = vec![4, 8];
let last = a.pop().unwrap();
println!("{}:{}", last, a.len());
}Pitfall: a Rust vector variable remaining in scope does not mean it is usable after iteration has consumed it.
Challenge
EasyCompress 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for Java Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler