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
cargo new my-app (預設,含 src/main.rs)cargo new my-lib --lib (含 src/lib.rs)cargo init / cargo init --libmy-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)
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]
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"
[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]
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 --libedition = "2024" 與 rust-version.gitignore(Cargo 自動產生)[lints] 啟用 clippy 檢查[profile.release] 最佳化選項// src/main.rs
// 最小的 Rust binary 專案入口
fn main() {
// 使用 println! 巨集輸出到標準輸出
println!("Hello, Rust!");
}
// src/main.rs
// 模組化專案:主程式引用 library crate
use my_app::config::Config;
use my_app::run;
fn main() -> anyhow::Result<()> {
// 從環境變數或預設值建立設定
let config = Config::from_env()?;
// 執行應用程式主邏輯
run(config)
}
// src/lib.rs
// Library root:公開模組與核心函式
pub mod config;
pub mod error;
use config::Config;
/// 應用程式主邏輯入口
pub fn run(config: Config) -> anyhow::Result<()> {
tracing::info!("Starting with config: {:?}", config);
Ok(())
}
// src/config.rs
// 設定模組:從環境變數讀取設定
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")?,
})
}
}
// crates/core/src/lib.rs
// 核心 domain 邏輯,不依賴外部框架
/// 領域模型:使用者
#[derive(Debug, Clone)]
pub struct User {
pub id: u64,
pub name: String,
pub email: String,
}
/// 使用者倉儲 trait,定義資料存取介面
pub trait UserRepository: Send + Sync {
/// 根據 ID 查詢使用者
fn find_by_id(&self, id: u64) -> anyhow::Result<Option<User>>;
/// 建立新使用者,回傳已儲存的使用者
fn create(&self, name: String, email: String) -> anyhow::Result<User>;
}
// crates/api/src/main.rs
// API 入口:組裝 core + 外部依賴
use core_lib::UserRepository;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// 初始化 tracing subscriber
tracing_subscriber::init();
tracing::info!("API server starting...");
// 此處組裝實際的 repository 實作
// let repo = PostgresUserRepo::new(&database_url).await?;
// start_server(repo).await
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+ |
# === 常用基礎依賴 ===
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 依賴 ===
[dev-dependencies]
pretty_assertions = "1.4"
tokio-test = "0.4"