Modules and Crates
Modules and crates in TypeScript vs Rust
Section titled “Modules and crates in TypeScript vs Rust”TypeScript uses ESM import/export for code organisation and npm (or similar) for third-party packages. Rust has two parallel concepts: modules (mod/use) for organising code within a project, and crates (packages managed by Cargo) for third-party dependencies.
Modules: mod and use
Section titled “Modules: mod and use”A module groups related items. Use pub to make items visible outside the module — the default is private.
// src/math.rs (a module file)pub fn add(a: i32, b: i32) -> i32 { a + b }fn helper() { } // private — not accessible outside
// src/main.rsmod math; // declare the module (pulls in math.rs)use math::add; // bring add into scope
fn main() { println!("{}", add(1, 2));}Modules can also be declared inline with mod name { ... }.
Crates and Cargo
Section titled “Crates and Cargo”A crate is Rust’s equivalent of an npm package. Cargo.toml is package.json. The workflow maps directly:
| npm | Cargo |
|---|---|
npm install serde | cargo add serde |
package.json | Cargo.toml |
node_modules/ | ~/.cargo/registry/ (shared cache) |
import { x } from 'pkg' | use pkg::x; |
Visibility rules
Section titled “Visibility rules”- Items are private by default — only accessible in the same module and its descendants.
pubmakes an item accessible from anywhere.pub(crate)restricts visibility to the current crate only.pub(super)restricts to the parent module.
// math.ts — named exportsexport function add(a: number, b: number): number { return a + b;}function helper() {} // not exported = module-private
// main.tsimport { add } from './math';console.log(add(1, 2));
// package.json dependency// "serde": "1.0" (hypothetical)// src/math.rspub fn add(a: i32, b: i32) -> i32 { a + b }fn helper() {} // private
// src/main.rsmod math;use math::add;
fn main() { println!("{}", add(1, 2));}
// Cargo.toml dependency// [dependencies]// serde = "1"Playground note: multi-file module trees require
cargo— run locally withcargo run.