Cargo是Rust的构建系统和包管理器。本文介绍Cargo的高级用法和项目组织最佳实践。 ## 工作空间(Workspace) ```toml [workspace] members = [ "core", "api", "cli", ] ``` ## 特性(Features) ```toml [features] default = ["json"] json = ["serde_json"] yaml = ["serde_yaml"] full = ["json", "yaml"] [dependencies] serde_json = { version = "1.0", optional = true } serde_yaml = { version = "0.9", optional = true } ``` ```rust #[cfg(feature = "json")] pub fn parse_json(input: &str) -> Result { serde_json::from_str(input) } ``` ## 条件编译 ```rust #[cfg(target_os = "linux")] fn platform_specific() { println!("Running on Linux"); } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } } ``` ## 常用命令 - cargo build --release:发布构建 - cargo test:运行测试 - cargo doc --open:生成文档 - cargo clippy:代码检查 - cargo fmt:格式化 - cargo tree:查看依赖树 - cargo outdated:检查依赖更新 - cargo audit:安全审计 ## 性能优化 ```toml [profile.release] opt-level = 3 lto = true codegen-units = 1 strip = true ``` 良好的项目组织和Cargo配置能让Rust项目更易维护和发布。