Rust Data Structures
A data structure is a shape for storing many values in one place. Rust provides arrays, tuples, Vecs, Strings and HashMaps as built-in shapes.
An array: a fixed row of slots
The size is set when you create it, and every value has the same type:
let scores = [10, 20, 30];
println!("first = {}", scores[0]);A vector: the same row, but it can grow
Start with one item, then push more on the end:
let mut cart = vec!["milk"];
cart.push("eggs");
println!("items = {}", cart.len());A tuple: different kinds packed together
The values keep their order, and you read them back with .0, .1, and so on:
let person = ("Ana", 34);
println!("{} is {}", person.0, person.1);A HashMap: look a value up by name
Store a price under a product name, then ask for it by that name:
use std::collections::HashMap;
let mut prices = HashMap::new();
prices.insert("apple", 3);
println!("apple = {}", prices["apple"]);Example
fn main() {
let fixed: [i32; 3] = [1, 2, 3];
let mut list = vec![10, 20];
list.push(30);
let point: (f64, f64) = (51.5, -0.12);
println!("array {:?} vec {:?} point {:?}", fixed, list, point);
}Key points
- Ask three questions: can the size change?
- How do I find an item?
- Does the order matter?
- Array [T; N]: a fixed number of items of the same type
- Tuple: a fixed number of items, each with its own type
- Vec<T>: a list that can grow and shrink
- String: growable text — a Vec of bytes with text rules
- HashMap: pairs of keys and values, for fast lookup by key
- Struct and Enum: tools to build your own shapes of data
In this example, three structures appear side by side. fixed is an array of three numbers. Its size is fixed in its type. list is a Vec, and push adds a third item at run time, so it grows. point is a tuple holding two decimal numbers as one value. The println! shows all three: the array, the list after growing, and the point.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Lines are read from a file one at a time, and all of them must be kept. Which structure fits best?