Marcin Jahn | Dev Notebook
  • Home
  • Programming
  • Technologies
  • Projects
  • About
  • Home
  • Programming
  • Technologies
  • Projects
  • About
  • An icon of the Core section Core
    • Programs Execution
    • Stack and Heap
    • Asynchronous Programming
      • Overview
      • Event Queues
      • Fibers
      • Stackless Coroutines
  • An icon of the .NET section .NET
    • HTTPClient
    • Async
      • How Async Works
      • TAP Tips
    • Equality
    • Comparisons
    • Enumerables
    • Unit Tests
    • Generic Host
    • Logging
    • Configuration
    • Records
    • Nullability
    • Garbage Collector
    • IL and Allocations
    • gRPC
    • Source Generators
    • Platform Invoke
    • ASP.NET Core
      • Overview
      • Middleware
      • Razor Pages
      • Routing in Razor Pages
      • Web APIs
      • Filters
      • Identity
      • Validation
      • Tips
    • Entity Framework Core
      • Overview
      • Testing
      • Tips
  • An icon of the Angular section Angular
    • Overview
    • Components
    • Directives
    • Services and DI
    • Routing
    • Observables (RxJS)
    • Forms
    • Pipes
    • HTTP
    • Modules
    • NgRx
    • Angular Universal
    • Tips
    • Standalone Components
  • An icon of the JavaScript section JavaScript
    • OOP
    • JavaScript - The Weird Parts
    • JS Functions
    • ES Modules
    • Node.js
    • Axios Tips
    • TypeScript
      • TypeScript Environment Setup
      • TypeScript Tips
    • React
      • React Routing
      • MobX
    • Advanced Vue.js Features
  • An icon of the Rust section Rust
    • Overview
    • Cargo
    • Basics
    • Ownership
    • Structures
    • Enums
    • Organization
    • Collections
    • Error Handling
    • Generics
    • Traits
    • Lifetimes
    • Closures
    • Raw Pointers
    • Smart Pointers
    • Concurrency
    • Testing
    • Tips
  • An icon of the C/C++ section C/C++
    • Compilation
    • Structures
    • OOP in C
    • Pointers
    • Strings
    • Dynamic Memory
    • argc and argv Visualization
  • An icon of the GTK section GTK
    • Overview
    • GObject
    • GJS
  • An icon of the CSS section CSS
    • Responsive Design
    • CSS Tips
    • CSS Pixel
  • An icon of the Unity section Unity
    • Unity
  • An icon of the Functional Programming section Functional Programming
    • Fundamentals of Functional Programming
    • .NET Functional Features
    • Signatures
    • Function Composition
    • Error Handling
    • Partial Application
    • Modularity
    • Category Theory
      • Overview
      • Monoid
      • Other Magmas
      • Functors
  • An icon of the Algorithms section Algorithms
    • Big O Notation
    • Array
    • Linked List
    • Queue
    • Hash Table and Set
    • Tree
    • Sorting
    • Searching
  • An icon of the Architecture section Architecture
    • What is architecture?
    • Domain-Driven Design
    • ASP.NET Core Projects
  • An icon of the Core section Core
    • Programs Execution
    • Stack and Heap
    • Asynchronous Programming
      • Overview
      • Event Queues
      • Fibers
      • Stackless Coroutines
  • An icon of the .NET section .NET
    • HTTPClient
    • Async
      • How Async Works
      • TAP Tips
    • Equality
    • Comparisons
    • Enumerables
    • Unit Tests
    • Generic Host
    • Logging
    • Configuration
    • Records
    • Nullability
    • Garbage Collector
    • IL and Allocations
    • gRPC
    • Source Generators
    • Platform Invoke
    • ASP.NET Core
      • Overview
      • Middleware
      • Razor Pages
      • Routing in Razor Pages
      • Web APIs
      • Filters
      • Identity
      • Validation
      • Tips
    • Entity Framework Core
      • Overview
      • Testing
      • Tips
  • An icon of the Angular section Angular
    • Overview
    • Components
    • Directives
    • Services and DI
    • Routing
    • Observables (RxJS)
    • Forms
    • Pipes
    • HTTP
    • Modules
    • NgRx
    • Angular Universal
    • Tips
    • Standalone Components
  • An icon of the JavaScript section JavaScript
    • OOP
    • JavaScript - The Weird Parts
    • JS Functions
    • ES Modules
    • Node.js
    • Axios Tips
    • TypeScript
      • TypeScript Environment Setup
      • TypeScript Tips
    • React
      • React Routing
      • MobX
    • Advanced Vue.js Features
  • An icon of the Rust section Rust
    • Overview
    • Cargo
    • Basics
    • Ownership
    • Structures
    • Enums
    • Organization
    • Collections
    • Error Handling
    • Generics
    • Traits
    • Lifetimes
    • Closures
    • Raw Pointers
    • Smart Pointers
    • Concurrency
    • Testing
    • Tips
  • An icon of the C/C++ section C/C++
    • Compilation
    • Structures
    • OOP in C
    • Pointers
    • Strings
    • Dynamic Memory
    • argc and argv Visualization
  • An icon of the GTK section GTK
    • Overview
    • GObject
    • GJS
  • An icon of the CSS section CSS
    • Responsive Design
    • CSS Tips
    • CSS Pixel
  • An icon of the Unity section Unity
    • Unity
  • An icon of the Functional Programming section Functional Programming
    • Fundamentals of Functional Programming
    • .NET Functional Features
    • Signatures
    • Function Composition
    • Error Handling
    • Partial Application
    • Modularity
    • Category Theory
      • Overview
      • Monoid
      • Other Magmas
      • Functors
  • An icon of the Algorithms section Algorithms
    • Big O Notation
    • Array
    • Linked List
    • Queue
    • Hash Table and Set
    • Tree
    • Sorting
    • Searching
  • An icon of the Architecture section Architecture
    • What is architecture?
    • Domain-Driven Design
    • ASP.NET Core Projects

Organization

Rust has a number of features that allow to manage code’s organization, including which details are exposed, which details are private, and what names are in each scope in programs. These features, sometimes collectively referred to as the module system, include:

  • Workspaces: acts like a solution in .NET. It may contain multiple packages.
  • Packages: one or more crates that provide a set of functionality. A package contains a Cargo.toml file. It’s like a project in .NET.
  • Crates: a binary or library. It’s a compilation unit for the compiler. Other languages treat a single file as a compilation unit
  • Modules: let us organize code within a crate into groups for readability and easy reuse.
  • Paths: A way of naming an item, such as a struct, function, or module.

Packages

A package contains crates. It can be as many binary crates as needed and just one library crate. We create packages with cargo new my-project-name.

Workspaces

A workspace may contain multiple packages. We need to define how packages are related (which one depends on which one).

We can specify project to run in a workspace with cargo run -p my-package.

Pckages in a workspace use the same versions of dependencies. There’s just one Cargo.lock file.

Modules

Modules control encapsulation. Some items might be public, others can be private. Modules may be nested.

Example:

mod front_of_house {
mod hosting {
fn add_to_waitlist() {}
fn seat_at_table() {}
}
mod serving {
fn take_order() {}
fn serve_order() {}
fn take_payment() {}
}
}

Modules may contain definitions of anything (modules, functions, structs, enums, etc.).

The root of every module is crate. It is either src/main.rs or src/lib.rs. There is a module tree similar to filesystem:

crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment

Paths

To refer to an entity we can use absolute or relative paths. We separate identifiers by ::.

Example:

mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
pub fn eat_at_restaurant() {
// Absolute path
crate::front_of_house::hosting::add_to_waitlist();
// Relative path
front_of_house::hosting::add_to_waitlist();
}

super acts like .. in Unix filesystems. We can use it to go up a module.

Encapsulation

  • All entities are private by default.

  • The privacy rules apply to structs, enums, functions, methods, and modules.

  • Items in a parent module cannot use the privte items inside child modules.

  • items in child modules can use items in their ancestor modules.

  • sibling items can access each other.

  • items can be made public with the pub keyword.

  • struct can be made public, but its fields will stay private unless they are individually made public:

    pub struct Breakfast {
    pub toast: String,
    seasonal_fruit: String,
    }
  • all enum’s options are public if enum itself is public.

Importing

The use keyword brings a path into the local scope so we don’t have to repeat paths all the time.

Example:

mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {}
}
}
use crate::front_of_house::hosting;
pub fn eat_at_restaurant() {
hosting::add_to_waitlist();
hosting::add_to_waitlist();
hosting::add_to_waitlist();
}

use is like a symbolic link in a filesystem.

Relative paths can be used with use as well.

There’s a “best practice” to bring functions via their containing module, and not the function name directly. That makes it more clear that the function is not local when we call it. Other items should be brought in directly, like the HashMap:

use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert(1, 2);
}

The imported entities may be re-exported with the use of pub use:

pub use crate::front_of_house::hosting;

Changing names

If there are entities with the same names (e.g. two structs) we can’t import them both directly. Instead, we should import their containing modules.

use std::io;
fn function1() -> fmt::Result {}
fn function2() -> io::Result<()> {}

We could also change name of an imported entity using the as keyword:

use std::fmt::Result;
use std::io::Result as IoResult;
fn function1() -> Result {}
fn function2() -> IoResult<()> {}

Importing all

The * (glob) operator allows us to bring in all items from some module:

use std::collections::*;

Re-exporting

Sometimes having a deep structure of types is good for the author of the crate, but troublesome for the users of the crate. Things can be reexported to change the way how they are visible outside.

pub use self::some_module::another_module::UsefulType

The UsefulType is available from the level of the file where we put that declaration. It will be also visible in the documentation of our crate.

References

Two ways to create module hierarchy in Rust (Reddit)

←  Enums
Collections  →
© 2023 Marcin Jahn | Dev Notebook | All Rights Reserved. | Built with Astro.