Filename: poem.txt
Listing 12-3: A poem by Emily Dickinson makes a good test case
Filename: src/main.rs
Listing 12-4: Reading the contents of the file specified by the second argument
In main
, we’ve added a new statement: fs::read_to_string
takes the , opens that file, and returns a Result<String>
of the file’s contents.
After that statement, we’ve again added a temporary println!
statement that prints the value of after the file is read, so we can check that the program is working so far.
Great! The code read and then printed the contents of the file. But the code has a few flaws. The main
function has multiple responsibilities: generally, functions are clearer and easier to maintain if each function is responsible for only one idea. The other problem is that we’re not handling errors as well as we could. The program is still small, so these flaws aren’t a big problem, but as the program grows, it will be harder to fix them cleanly. It’s good practice to begin refactoring early on when developing a program, because it’s much easier to refactor smaller amounts of code. We’ll do that next.