Raw data, clear context.

[
[
[

]
]
]

A text-file analyser needs one result per file. Start with notes.txt: its name and two counts should travel together. If you store the counts separately, you have to keep track of which pair belongs to which file. Give the results a shared type called FileStats and use one value of that type for each file.

The struct definition names the type and lists its fields, which can have different types.[1] The record owns its file name because name is a String.[1]

The fields lines and words are both usize. They need distinct names because they count different things.

Put the example in src/main.rs in a Cargo binary project. Run it from the directory containing Cargo.toml.

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

src/main.rs
Rust
struct FileStats {
name: String,
lines: usize,
words: usize,
}
fn main() {
let report = FileStats {
words: 41,
name: String::from("notes.txt"),
lines: 6,
};
println!("File: {}", report.name);
println!("Lines: {}", report.lines);
println!("Words: {}", report.words);
}
Shell
cargo run --quiet
Output
$ cargo run --quiet
File: notes.txt
Lines: 6
Words: 41
exit=0

The programme supplies the counts directly: six lines and 41 words. You can run it without creating notes.txt. The file name is a label for the sample data; the programme never opens the file.

Inside main, the braces after FileStats supply values for one instance. The colon now separates each field name from its value, and the fields can appear in any order.[2]

Here words appears first in the initialiser and last in the definition. The two places still refer to the same field.

A field is read with a dot: report.words selects the word count.[1]

A FileStats record for notes.txt shows three named fields: name (String), lines (usize) with the sample value 6 and words (usize) with the sample value 41.
Each row pairs a field type with its value in the sample record. The counts are supplied by the programme.

Leave out a field

Remove the words: 41, line from the initialiser and run the same command. The compiler reports E0063 and names the missing words field. The programme prints nothing in that run.

When you supply the fields explicitly as above, give each field a value exactly once.[4]

Try a second file

Restore the missing line, then create another FileStats value called empty for empty.txt, with both counts set to zero. Print empty.words after the existing output and check that it prints 0 while report.words still prints 41.

In the next lesson, you’ll give FileStats its own method so the type can format a summary of the fields it holds.

Browse Rust, one step at a time

Sources

  1. The Rust Book: Defining and Instantiating Structs
  2. The Rust Reference: Struct expressions
  3. The Cargo Book: cargo run
  4. Rust compiler error index: E0063

One response

  1. Rust 015: Methods that belong to a type – read0nly Avatar

    […] Previous lesson: Giving data a shape […]

    Like

Leave a Reply