data_02_select_columns/data_02_select_columns.rs
1//! # data_02 — Selecting columns by name
2//!
3//! Run: `cargo run -p matten-data --example data_02_select_columns`
4//!
5//! ## What this shows
6//! Choosing a subset of columns by name, in the order you ask for them, and what
7//! happens when you ask for a column that does not exist.
8//!
9//! ## Teaching points
10//! - selection is **by name**, and the output column order matches your request
11//! (not the original CSV order);
12//! - selecting an unknown column is a clean, structured error, never a panic;
13//! - selection does not convert anything — it returns another `Table`.
14
15use matten_data::{MattenDataError, Table};
16
17fn main() -> Result<(), MattenDataError> {
18 let csv = "\
19region,sales,cost,quantity
20north,100,40,5
21south,150,45,7";
22
23 let table = Table::from_csv_str(csv)?;
24
25 // Ask for a subset in a deliberately different order than the CSV.
26 let reordered = table.select_columns(["quantity", "sales"])?;
27 println!("selected names: {:?}", reordered.column_names());
28
29 // The output order is exactly what was requested.
30 assert_eq!(
31 reordered.column_names(),
32 &["quantity".to_string(), "sales".to_string()]
33 );
34 assert_eq!(reordered.column_count(), 2);
35 assert_eq!(reordered.row_count(), 2);
36
37 // Asking for a column that does not exist is a structured error.
38 match table.select_columns(["sales", "profit"]) {
39 Err(MattenDataError::MissingColumn { name }) => {
40 println!("missing column reported: {name}");
41 assert_eq!(name, "profit");
42 }
43 other => panic!("expected MissingColumn, got {other:?}"),
44 }
45
46 println!("data_02_select_columns: OK");
47 Ok(())
48}