SuperAPI AI Directory

rust-project-structure

Coding & development

View repository

Updated 10-15 21:48

About this skill

Rust Project Structure & Scafold

Based on The Rust Programming Language ch 7 and The Rust Reference ch 7 (Items & Modules).

Capability Boundaries

✅ Strengths

  1. Concepts and conventions of packages and crates (binary/library)
  2. Module file system layout (src/lib.rs, src/main.rs, submodule files/directories)
  3. mod declarations and module nesting
  4. pub visibility system (pub, pub(crate), pub(super), pub(self))
  5. use path patterns (absolute/relative, nested A::{B,C}、glob A::*, aliases A as B、re-export)
  6. External crate references
  7. Workspace multi-package project layout
  8. Conditional compilation and cfg attributes
  9. Project templates and scaffolding (cargo new, cargo-generate)

⚠️ Prerequisites

  1. Understanding of Rust ownership and module basics (can refer to the rust-1.93 skill)

❌ Out of Scope

  1. Cargo.toml configuration → use the rust-cargo-build skill
  2. Rust syntax basics → use the rust-1.93 skill
  3. Test organization → use the rust-testing skill

When to Use

  • "Organize Rust project structure"
  • "How do modules reference each other"
  • "pub visibility rules"
  • "Multi-crate workspace layout"

Data Privacy

This skill does not collect, store, or transmit any user data.


1. Packages and Crates

// package 二进制 + 库混合布局
my-project/
├── Cargo.toml
├── src/
│   ├── lib.rs        # 库 crate 根
│   └── main.rs       # 二进制 crate 根

// 多二进制 crate 布局
my-project/
├── Cargo.toml
└── src/
    ├── lib.rs
    ├── main.rs
    └── bin/
        ├── other.rs
        └── another.rs  // 每个 bin/ 文件独立二进制

2. Module System

// lib.rs — 声明模块
pub mod front_of_house;      // 从 front_of_house.rs 或 front_of_house/mod.rs 加载
mod back_of_house;           // 私有模块,仅当前 crate 可见
pub(crate) mod utils;        // 对整个 crate 公开但外部不可见

// front_of_house.rs
pub mod hosting;             // 从 hosting.rs 加载

// front_of_house/hosting.rs
pub fn add_to_waitlist() {}
fn seat_at_table() {}        // 默认私有

3. Visibility System

pub fn public_fn() {}             // 外部可见
fn private_fn() {}                // 默认私有(当前模块 + 子模块)
pub(crate) fn crate_visible() {}  // 整个 crate 可见
pub(super) fn parent_visible() {} // 父模块可见
pub(self) fn module_visible() {}  // 当前模块可见(等价默认)
pub(in crate::foo) fn restricted() {}  // 指定路径可见(nightly)

4. use Path Patterns

// 绝对路径 — crate:: 或 根
use crate::front_of_house::hosting;
use std::collections::HashMap;

// 相对路径 — self:: 或 super::
use self::back_of_house::Cook;
use super::parent_module::helper;

// 嵌套路径
use std::{cmp::Ordering, io};
use std::io::{self, Write};

// Glob(谨慎使用)
use std::collections::*;

// 别名
use std::fmt::Result as FmtResult;

// 重新导出(pub use)
pub use crate::front_of_house::hosting;
// 外部现在可以通过 my_crate::hosting 访问

5. Workspace

# Cargo.toml (workspace root)
[workspace]
members = [
    "crates/core",
    "crates/utils",
    "app",
]
resolver = "3"
my-workspace/
├── Cargo.toml          # workspace 定义
├── crates/
│   ├── core/
│   │   ├── Cargo.toml  # [package] + [dependencies]
│   │   └── src/lib.rs
│   └── utils/
│       ├── Cargo.toml
│       └── src/lib.rs
├── app/
│   ├── Cargo.toml
│   └── src/main.rs
└── Cargo.lock          # 共享 lock 文件
# crates/utils/Cargo.toml — 引用 workspace 内 crate
[dependencies]
core = { path = "../core" }

6. Conditional Compilation

#[cfg(target_os = "linux")]
fn only_linux() {}

#[cfg(not(target_os = "windows"))]
fn not_windows() {}

#[cfg(feature = "serde")]
fn with_serde() {}

// cfg! 宏(运行时检查)
if cfg!(target_os = "linux") {
    println!("Running on Linux");
}

// cfg_attr
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
struct Config;

7. Project Scaffolding

cargo new my-app              # 二进制项目
cargo new my-lib --lib        # 库项目
cargo init                    # 当前目录初始化
cargo new --vcs none          # 不初始化 git

# 使用模板(需要 cargo-generate)
cargo install cargo-generate
cargo generate --git https://github.com/rust-unofficial/patterns.git

Workflow

Step 1. Confirm project type — single-crate package, multi-crate package, or workspace Step 2. Choose naming conventions — determine binary and library names based on project purpose (snake_case) Step 3. Plan module hierarchy — starting from lib.rs, split module files and directories by functional domain Step 4. Design visibility interfaces — determine which types/functions are pub/pub(crate) or private Step 5. Organize paths and use — configure use imports, ensuring module visibility rules are not violated Step 6. Verify — cargo check confirms compilation passes, check that IDE module navigation works normally

Gotchas

  1. crate:: vs ::crate_name:: - crate:: references the current crate root; ::other_crate:: is an absolute path referencing an external crate
  2. pub(crate) is unavailable in the 2015 edition - requires edition 2018+
  3. mod.rs is deprecated - since the 2018 edition, module_name.rs is recommended over module_name/mod.rs
  4. The workspace resolver version affects feature resolution - edition 2021+ automatically selects resolver 3
  5. The #[path] attribute bypasses file system conventions - after use, module paths no longer follow the default file tree

Official reference