Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Practical System Programming for Rust Developers

You're reading from  Practical System Programming for Rust Developers

Product type Book
Published in Dec 2020
Publisher Packt
ISBN-13 9781800560963
Pages 388 pages
Edition 1st Edition
Languages
Author (1):
Prabhu Eshwarla Prabhu Eshwarla
Profile icon Prabhu Eshwarla

Table of Contents (17) Chapters

Preface 1. Section 1: Getting Started with System Programming in Rust
2. Chapter 1: Tools of the Trade – Rust Toolchains and Project Structures 3. Chapter 2: A Tour of the Rust Programming Language 4. Chapter 3: Introduction to the Rust Standard Library 5. Chapter 4: Managing Environment, Command Line, and Time 6. Section 2: Managing and Controlling System Resources in Rust
7. Chapter 5: Memory Management in Rust 8. Chapter 6: Working with Files and Directories in Rust 9. Chapter 7: Implementing Terminal I/O in Rust 10. Chapter 8: Working with Processes and Signals 11. Chapter 9: Managing Concurrency 12. Section 3: Advanced Topics
13. Chapter 10: Working with Device I/O 14. Chapter 11: Learning Network Programming 15. Chapter 12: Writing Unsafe Rust and FFI 16. Other Books You May Enjoy

Handling errors and returning values

In this section, we'll learn about the built-in error handling support in the std::io module. Handling recoverable errors in an appropriate manner makes Rust programs more robust.

In the code examples we've seen so far, we've used the unwrap() function to extract the return value from the std::io module methods and associated functions, such as Read, Write, BufReader, and BufWriter. However, this is not the correct way to handle errors. The std::io module has a specialized Result type that is returned from any function or method in this module that may produce an error.

Let's rewrite the previous example (of chaining readers) using the io::Result type as the return value from the function. This allows us to use the ? operator to directly pass errors back from the main() function, instead of using the unwrap() function:

use std::fs::File;
use std::io::Read;
fn main() -> std::io::Result<()> {
   ...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}