| name | rust-project-init |
| description | Rust 專案初始化與 Cargo 設定技能。涵蓋 cargo new、cargo init、workspace 多專案管理、 Cargo.toml manifest 設定模板、目錄結構最佳實踐、edition 2024 設定、features 管理、 profile 最佳化設定、依賴管理策略。觸發關鍵詞:Rust project init, cargo new, cargo init, Cargo.toml, workspace, Rust project structure, cargo workspace, Rust boilerplate, Rust starter template, Rust project setup, new Rust project, Rust directory layout
|
Rust 專案初始化 (rust-project-init)
適用場景
- 建立新的 Rust 專案(binary 或 library)
- 設定 Cargo workspace 管理多個 crate
- 規劃專案目錄結構
- 撰寫或調整 Cargo.toml 設定
- 設定 build profiles (dev/release)
- 管理 features 與 conditional compilation
核心知識
Cargo 專案類型
- Binary crate:
cargo new my-app (預設,含 src/main.rs)
- Library crate:
cargo new my-lib --lib (含 src/lib.rs)
- 既有目錄:
cargo init / cargo init --lib
推薦目錄結構(單一 crate)
my-project/
├── Cargo.toml
├── Cargo.lock # binary 才需 commit
├── src/
│ ├── main.rs # binary entry
│ ├── lib.rs # library entry
│ └── bin/ # 多個 binary
│ └── other.rs
├── tests/ # integration tests
│ └── integration_test.rs
├── benches/ # benchmarks
│ └── my_bench.rs
├── examples/ # 範例程式
│ └── demo.rs
└── build.rs # build script (optional)
Workspace 結構(多 crate)
my-workspace/
├── Cargo.toml # [workspace] 定義
├── Cargo.lock
├── crates/
│ ├── core/
│ │ ├── Cargo.toml
│ │ └── src/lib.rs
│ ├── api/
│ │ ├── Cargo.toml
│ │ └── src/main.rs
│ └── utils/
│ ├── Cargo.toml
│ └── src/lib.rs
└── README.md
Workspace Cargo.toml 模板
[workspace]
resolver = "2"
members = ["crates/*"]
[workspace.package]
edition = "2024"
rust-version = "1.85"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/project"
[workspace.dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = { version = "1.44", features = ["full"] }
anyhow = "1.0"
thiserror = "2.0"
tracing = "0.1"
單一專案 Cargo.toml 模板
[package]
name = "my-app"
version = "0.1.0"
edition = "2024"
rust-version = "1.85"
description = "A short description"
license = "MIT OR Apache-2.0"
readme = "README.md"
[dependencies]
[dev-dependencies]
[build-dependencies]
[features]
default = []
[profile.dev]
opt-level = 0
debug = true
[profile.release]
opt-level = 3
lto = "thin"
strip = true
codegen-units = 1
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
enum_glob_use = "deny"
pedantic = { level = "warn", priority = -1 }
Features 管理
[features]
default = ["json"]
json = ["dep:serde_json"]
full = ["json", "async"]
async = ["dep:tokio"]
[dependencies]
serde_json = { version = "1.0", optional = true }
tokio = { version = "1.44", optional = true, features = ["full"] }
常用初始化步驟
cargo new my-project 或 cargo new my-project --lib
- 設定
edition = "2024" 與 rust-version
- 新增
.gitignore(Cargo 自動產生)
- 設定
[lints] 啟用 clippy 檢查
- 設定
[profile.release] 最佳化選項
- 新增 CI 設定(GitHub Actions)
程式碼範例
Basic: 最小 binary 專案
fn main() {
println!("Hello, Rust!");
}
Intermediate: 模組化專案結構
use my_app::config::Config;
use my_app::run;
fn main() -> anyhow::Result<()> {
let config = Config::from_env()?;
run(config)
}
pub mod config;
pub mod error;
use config::Config;
pub fn run(config: Config) -> anyhow::Result<()> {
tracing::info!("Starting with config: {:?}", config);
Ok(())
}
use serde::Deserialize;
#[derive(Debug, Deserialize)]
pub struct Config {
pub port: u16,
pub database_url: String,
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
Ok(Self {
port: std::env::var("PORT")
.unwrap_or_else(|_| "8080".into())
.parse()?,
database_url: std::env::var("DATABASE_URL")?,
})
}
}
Advanced: Workspace 多 crate 專案
#[derive(Debug, Clone)]
pub struct User {
pub id: u64,
pub name: String,
pub email: String,
}
pub trait UserRepository: Send + Sync {
fn find_by_id(&self, id: u64) -> anyhow::Result<Option<User>>;
fn create(&self, name: String, email: String) -> anyhow::Result<User>;
}
use core_lib::UserRepository;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::init();
tracing::info!("API server starting...");
Ok(())
}
常見錯誤對照表
| 錯誤訊息 | 原因 | 修復方式 |
|---|
failed to parse manifest | Cargo.toml 語法錯誤 | 檢查 TOML 格式,常見:忘記引號、縮排錯誤 |
no targets specified in the manifest | 缺少 src/main.rs 或 src/lib.rs | 建立對應的入口檔案 |
found a virtual manifest but expected a package manifest | 在 workspace root 執行需要 package 的指令 | 使用 -p <package> 指定 crate |
current package believes it's in a workspace | package.workspace 路徑錯誤 | 檢查 workspace 成員路徑設定 |
edition 2024 is not supported | Rust toolchain 版本太舊 | rustup update 升級到 1.85+ |
Cargo.toml 依賴模板
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1.44", features = ["full"] }
anyhow = "1.0"
thiserror = "2.0"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
clap = { version = "4.5", features = ["derive"] }
reqwest = { version = "0.12", features = ["json"] }
[dev-dependencies]
pretty_assertions = "1.4"
tokio-test = "0.4"
參考來源