How it works...

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.

BufRead is a trait, and the most common way to get one is from a BufReader that is constructed from some type that implements Read; here, a file. The file is opened for writing with File::create and for reading with File::open.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.71.115