Book Image

Practical System Programming for Rust Developers

By : Prabhu Eshwarla
Book Image

Practical System Programming for Rust Developers

By: Prabhu Eshwarla

Overview of this book

Modern programming languages such as Python, JavaScript, and Java have become increasingly accepted for application-level programming, but for systems programming, C and C++ are predominantly used due to the need for low-level control of system resources. Rust promises the best of both worlds: the type safety of Java, and the speed and expressiveness of C++, while also including memory safety without a garbage collector. This book is a comprehensive introduction if you’re new to Rust and systems programming and are looking to build reliable and efficient systems software without C or C++. The book takes a unique approach by starting each topic with Linux kernel concepts and APIs relevant to that topic. You’ll also explore how system resources can be controlled from Rust. As you progress, you’ll delve into advanced topics. You’ll cover network programming, focusing on aspects such as working with low-level network primitives and protocols in Rust, before going on to learn how to use and compile Rust with WebAssembly. Later chapters will take you through practical code examples and projects to help you build on your knowledge. By the end of this Rust programming book, you will be equipped with practical skills to write systems software tools, libraries, and utilities in Rust.
Table of Contents (17 chapters)
1
Section 1: Getting Started with System Programming in Rust
6
Section 2: Managing and Controlling System Resources in Rust
12
Section 3: Advanced Topics

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<()> {
   ...