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]
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());}
cargo run --quiet
$ cargo run --quietAt index 2: 15 kgParcel: 12 kgParcel: 18 kgParcel: 15 kgParcels: 3exit=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.

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
Leave a Reply