Book Image

Mastering Rust - Second Edition

By : Rahul Sharma, Vesa Kaihlavirta
Book Image

Mastering Rust - Second Edition

By: Rahul Sharma, Vesa Kaihlavirta

Overview of this book

Rust is an empowering language that provides a rare combination of safety, speed, and zero-cost abstractions. Mastering Rust – Second Edition is filled with clear and simple explanations of the language features along with real-world examples, showing you how you can build robust, scalable, and reliable programs. This second edition of the book improves upon the previous one and touches on all aspects that make Rust a great language. We have included the features from latest Rust 2018 edition such as the new module system, the smarter compiler, helpful error messages, and the stable procedural macros. You’ll learn how Rust can be used for systems programming, network programming, and even on the web. You’ll also learn techniques such as writing memory-safe code, building idiomatic Rust libraries, writing efficient asynchronous networking code, and advanced macros. The book contains a mix of theory and hands-on tasks so you acquire the skills as well as the knowledge, and it also provides exercises to hammer the concepts in. After reading this book, you will be able to implement Rust for your enterprise projects, write better tests and documentation, design for performance, and write idiomatic Rust code.
Table of Contents (19 chapters)

Custom errors and the Error trait

A non-trivial project that has varied functionality is often spread across modules. With an organization, it's more informative to provide module-specific error messages and information for the user. Rust allows us to create custom error types that can help us achieve more granular error reports from our application. Without custom errors that are specific to our project, we might have to use existing error types in the standard library, which may not be relevant to our API's operations and will not give precise information to users if things go wrong with an operation in our module.

In languages that have exceptions, such as Java, the way you create custom exceptions is by inheriting from the base Exception class and overriding its methods and member variables. While Rust doesn't have type-level inheritance, it has trait inheritance...