Modules and Visibility
Lesson 3 of 48 in Coddy's Rust for JavaScript Developers course.
An ES module is a file: names it does not export stay private to that file, and import loads it when the program starts. A Rust module is a namespace and privacy boundary inside one compiled crate. It need not be its own file, and a file joins the crate only when a parent declares it with mod. This course compiles one root file with sibling module declarations, without Cargo. The standalone examples put the module inline so you can run the complete program. The JavaScript version hides a helper inside a closure, the classic module pattern; Rust gets the same privacy without any runtime object. Rust items are private by default. pub makes an item accessible from outside its module, but the enclosing module path still controls who can reach it. Calling greeting::word() follows a path the compiler resolves; no namespace object exists at runtime. Reaching a private item is a compile error, not an undefined property discovered while the program runs. Visibility is independent of ownership.
Complete standalone JavaScript program:
const greeting = (() => {
const base = () => "hello";
return { word: () => base() + "!" };
})();
console.log(greeting.word());
console.log(typeof greeting.base);
JavaScript output:
hello!
undefined
Complete standalone Rust program:
mod greeting {
fn base() -> &'static str { "hello" }
pub fn word() -> String { format!("{}!", base()) }
}
fn main() {
println!("{}", greeting::word());
}
Rust output:
hello!
Challenge
EasyCompute packet storage. Input contains payload byte count and packet count, separated by whitespace, both from 0 to 1000. Required API: pub fn packet_size(payload: u32) -> u32 adds a private overhead of 6 bytes; pub fn batch_size(payload: u32, count: u32) -> u32 returns the storage for that many identical packets, including overhead for each. batch_size must use the packet-size rule. Output one:batch, using decimal integers with no spaces. Implement the public API in packet.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, packet.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod packet;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(packet::packet_size(13), 19);
assert_eq!(packet::batch_size(13, 7), 133);
assert_eq!(packet::packet_size(0), 6);
assert_eq!(packet::batch_size(55, 0), 0);
assert_eq!(packet::batch_size(0, 9), 54);
assert_eq!(packet::packet_size(13), 19);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for JavaScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler