Book Image

The Complete Rust Programming Reference Guide

By : Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger
Book Image

The Complete Rust Programming Reference Guide

By: Rahul Sharma, Vesa Kaihlavirta, Claus Matzinger

Overview of this book

Rust is a powerful language with a rare combination of safety, speed, and zero-cost abstractions. This Learning Path is filled with clear and simple explanations of its features along with real-world examples, demonstrating how you can build robust, scalable, and reliable programs. You’ll get started with an introduction to Rust data structures, algorithms, and essential language constructs. Next, you will understand how to store data using linked lists, arrays, stacks, and queues. You’ll also learn to implement sorting and searching algorithms, such as Brute Force algorithms, Greedy algorithms, Dynamic Programming, and Backtracking. As you progress, you’ll pick up on using Rust for systems programming, network programming, and the web. You’ll then move on to discover a variety of techniques, right from writing memory-safe code, to building idiomatic Rust libraries, and even advanced macros. By the end of this Learning Path, you’ll be able to implement Rust for enterprise projects, writing better tests and documentation, designing for performance, and creating idiomatic Rust code. This Learning Path includes content from the following Packt products: • Mastering Rust - Second Edition by Rahul Sharma and Vesa Kaihlavirta • Hands-On Data Structures and Algorithms with Rust by Claus Matzinger
Table of Contents (29 chapters)
Title Page
Copyright
About Packt
Contributors
Preface
Index

Modules


Before we explore more about Cargo, we need to be familiar with how Rust organizes our code. We had a brief glimpse at modules in the previous chapter. Here, we will cover them in detail. Every Rust program starts with a root module. If you are creating a library, your root module is the lib.rs file. If you are creating an executable, the root module is any file with a main function, usually main.rs. When your code gets large, Rust lets you split it into modules. To provide flexibility in organizing a project, there are multiple ways to create modules.

Nested modules

The simplest way to create a module is by using the mod {} block within an existing module. Consider the following code:

// mod_within.rs

mod food {
    struct Cake;
    struct Smoothie;
    struct Pizza;
}

fn main() {
    let eatable = Cake;
}

We created an inner module named food. To create a module within an existing one, we use the mod keyword, followed by the name of the module, food, followed by a pair of braces...