The text-file analyser stores each file’s name, line count and word count in a FileStats record. Give that record a summary method so callers can print the same kind of summary without repeating the format string.
An impl FileStats block attaches functions to the FileStats type.[1] A method is an associated function whose first parameter, self, represents the value it is called on.[1]
Put this example in src/main.rs in the Cargo binary project from lesson 002. Run the command from the directory containing Cargo.toml.
The quiet flag suppresses Cargo’s log messages.[4]
struct FileStats { name: String, lines: usize, words: usize,}impl FileStats { fn summary(&self) -> String { format!("{}: {} lines, {} words", self.name, self.lines, self.words) }}fn main() { let report = FileStats { name: String::from("notes.txt"), lines: 6, words: 41, }; println!("{}", report.summary()); println!("Stored word count: {}", report.words);}
cargo run --quiet
$ cargo run --quietnotes.txt: 6 lines, 41 wordsStored word count: 41exit=0
The output block shows the command, the programme’s two lines of stdout and the exit status. This run used Rust 1.99.1. The counts are sample values. You can run the example without creating notes.txt.
The method declares &self, short for self: &Self.[1] In this block Self means FileStats, so the method receives a shared reference to the record.[1]

In the call report.summary(), report is the receiver, and Rust automatically borrows it to call this method.[2] format! builds a String by putting the field values into the placeholders in order.[3]
The parentheses in report.summary() are empty because this method takes no arguments beyond its receiver. The first println! prints the returned string, and the second reads report.words after the call. The value is still 41.
When the dot call fails
Replace &self with a named parameter like item: &FileStats and the function still belongs to the type, but now it has no receiver.[1]
Change the signature that way and replace self. with item. in the body. Run the same command with the dot call unchanged: the compiler gives E0599 for summary. Restore &self and the original field reads to get the method back.
Try an empty report
Add another FileStats for empty.txt with both counts set to zero. Print its summary using the same method and check that the first report still shows 41 words.
Next, use an enum to represent alternatives in a single type.
Previous lesson: Giving data a shape
Browse Rust, one step at a time
Leave a Reply