In this recipe, we write a three-line message to a file, lines.txt. We assign the string lines.txt to a variable named path, which we pass as an argument to File::create(path) that creates the file, and we assign it to a variable output. Using the write! macro, we write a string "Rust Fun" to the mutable output variable.
We read the file, then read back with File::open(path) and assign it to the input variable. We create a variable named buffered that stores the content of the file; we then read each line of the file with the Lines iterator created by BufRead::lines using a for loop and print it.
The error-chain crate is a library for consistent and reliable error-handling that makes it easier to take full advantage of Rust's powerful error-handling features, without the overhead of maintaining boilerplate error types and conversions. It implements a strategy for defining your own error types, as well as conversions from others' error types.
The basic pattern we use here has a function named run() that produces a Result type that acts like a real main function. We use the error-chain crate to make ? work within run. This is using the error_chain! macro from the error-chain crate to define a custom Error and Result type, along with automatic conversions from the crate error types. The automatic conversions make the ? operator work. The quick_main! macro generates the actual main function and prints out the error if it occurs during the course of execution.
We return Ok(()) to the quick_run! macro to ensure that the program executed successfully without any errors.