Raw data, clear context.

[
[
[

]
]
]

Two parcels have been weighed for the loading bay when a third arrives. Add its weight to the list, check the new entry and print every weight in the order it was recorded.

A Rust vector holds elements of one type, and vec! creates one with the values you supply.[1] An array has a fixed length as part of its type.[2] A Vec can grow: push adds an element at the end.[3]

Here Vec<u32> makes the element type explicit: the example uses whole, non-negative weights in kilograms. The list starts with 12 and 18; the call to push adds 15.

The binding needs mut so the programme can change the vector.[1]

Put the example in src/main.rs in a Cargo binary project, then run the command below from the project directory.

The quiet flag suppresses Cargo’s own log messages.[4]

src/main.rs
Rust
fn main() {
let mut weights: Vec<u32> = vec![12, 18];
weights.push(15);
let index = 2;
println!("At index {index}: {} kg", weights[index]);
for weight in &weights {
println!("Parcel: {weight} kg");
}
println!("Parcels: {}", weights.len());
}
Shell
cargo run --quiet
Output
$ cargo run --quiet
At index 2: 15 kg
Parcel: 12 kg
Parcel: 18 kg
Parcel: 15 kg
Parcels: 3
exit=0

The first line of programme output comes from a single lookup. It prints the new parcel’s weight, 15 kg, at index 2. The loop then prints all three weights, starting with the original two, and the final line gives the parcel count.

Before the push, indices 0 and 1 hold 12 kg and 18 kg. After the push, those entries keep their positions and 15 kg appears at index 2. The length goes from 2 to 3.
Appending the third parcel adds one entry at the end. The new weight occupies index 2, and the first two weights keep their original indices.

The loop uses &weights to borrow each element, leaving the vector available for the next line.[1] Calling len() gives the number of elements in the list.[3]

The first index past the end

Rust counts vector indices from zero.[1] Direct indexing panics when the requested index is outside the vector.[3] If an index can be missing, get returns None for an out-of-range request.[1]

Here the valid indices are 0, 1 and 2. Set index to weights.len() and the programme asks for a fourth entry. In that run it panics before printing any weights.

Try another parcel

Add a 21 kg parcel with a second push, before the lookup. Keep the selected index at 2. Check that it still reads 15 kg, that 21 kg appears last in the loop and that the count rises to four.

Next time, a struct will group named fields for the first part of a text-file analyser.

Browse Rust, one step at a time

Sources

  1. The Rust Book: Storing Lists of Values with Vectors
  2. Rust standard library: array
  3. Rust standard library: Vec
  4. The Cargo Book: cargo run

Leave a Reply