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]
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);}
cargo run --quiet
$ cargo run --quietFile: notes.txtLines: 6Words: 41exit=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]

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