← 講座に戻る: Rust from scratch

Modules, visibility and crates

動画は近日公開

While your program fits in one file, everything is simple. When it grows, you need to organize it: split the code by topic, decide which parts are public and which are internal details, and reuse code from others. Rust offers its module and crate system for that. A crate is the compilation unit: a binary (with main) or a library. A package is what cargo manages: a Cargo.toml with one or more crates. Inside a crate, code is organized into modules.

Modules and pub

A module is declared with mod name { ... }. Everything inside is private by default: only the module itself and its children can see it. To expose something to the outside you mark it with pub: functions, structs, enums, constants and also each field of a struct, separately. With this you can hide internal details and offer a small, stable API. Modules can be nested, and you access with paths separated by ::, like shop::orders::total.

rust
mod shop {
    pub struct Product {
        pub name: String,
        price_cents: u32, // private: only code inside `shop` can touch it
    }

    impl Product {
        pub fn new(name: &str, price_cents: u32) -> Product {
            Product { name: name.to_string(), price_cents }
        }
        pub fn price(&self) -> f64 {
            self.price_cents as f64 / 100.0
        }
    }

    pub mod cart {
        use super::Product;

        pub fn total(items: &[Product]) -> f64 {
            items.iter().map(|p| p.price()).sum()
        }
    }

    fn secret_discount() -> u32 { 10 } // private helper
}

use shop::cart;
use shop::Product;

fn main() {
    let items = vec![Product::new("tea", 350), Product::new("cake", 575)];
    println!("{} costs {}", items[0].name, items[0].price());
    println!("total = {:.2}", cart::total(&items));
    // println!("{}", items[0].price_cents); // error: field is private
    // shop::secret_discount();              // error: function is private
}

Two path keywords help: crate:: starts from the crate root, and super:: goes up one level to the parent module. The use declaration brings a name into scope so you do not repeat the long path; you can rename with as and bring several with braces: use std::collections::{HashMap, HashSet}. By convention import functions through their module (cart::total) and types directly (Product).

Modules in files

When a module grows, you move it to its own file. In src/main.rs you write only mod shop; (with a semicolon) and Rust looks for the content in src/shop.rs or in src/shop/mod.rs. A submodule cart of shop lives in src/shop/cart.rs. The file does not need to repeat mod shop { }: its content is the body of the module. This mechanism is just a way to distribute the text; modules work exactly as in the previous example.

rust
// Project layout (shown as comments; not a runnable single file)
//
// my_app/
//   Cargo.toml
//   src/
//     main.rs        -> mod shop; use shop::cart;
//     lib.rs         -> (optional) library part of the same package
//     shop.rs        -> pub mod cart; pub struct Product { ... }
//     shop/
//       cart.rs      -> pub fn total(...)

fn main() {
    println!("see layout above");
}

External crates and Cargo.toml

To use a community library, you add it in the [dependencies] section of Cargo.toml with its name and version, and cargo downloads and compiles it from crates.io. For example, rand = "0.8" or serde = { version = "1", features = ["derive"] }. The cargo add name command writes the line for you. Cargo stores the exact versions it resolved in Cargo.lock, so your builds are reproducible. In this course we use only the standard library, but in real projects you will almost always use some external crate.

toml
# Cargo.toml (example, not Rust code)
[package]
name = "my_app"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8"
serde = { version = "1", features = ["derive"] }

# cargo add rand      -> adds the line for you
# cargo doc --open    -> opens the documentation of your dependencies
rust
mod geometry {
    pub mod shapes {
        pub struct Circle {
            pub radius: f64,
        }
        pub fn area(c: &Circle) -> f64 {
            3.14159 * c.radius * c.radius
        }
    }

    pub fn describe(c: &shapes::Circle) -> String {
        format!("circle of area {:.2}", shapes::area(c))
    }
}

use geometry::shapes::Circle;

fn main() {
    let c = Circle { radius: 2.0 };
    println!("{}", geometry::describe(&c));
}

理解度チェック

問題 1 / 4

What visibility does an item inside a module have by default?

✎ マイノート

このブラウザにのみ保存されます。ログインするとアカウントに保存できます。0/5000 文字

← 前へ次へ →