Rust 安装并创建hello world项目
【摘要】 在 Rust 中创建项目通常使用 cargo(Rust 的包管理器和构建工具)。以下是详细步骤和常见操作: 1. 安装 Rust确保已安装 Rust 和 Cargo(通过 rustup):curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shsource $HOME/.cargo/env # 加载环境变量(Linux/m...
在 Rust 中创建项目通常使用 cargo(Rust 的包管理器和构建工具)。以下是详细步骤和常见操作:
1. 安装 Rust
确保已安装 Rust 和 Cargo(通过 rustup):
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env # 加载环境变量(Linux/macOS)
验证安装:
rustc --version
cargo --version
2. 创建新项目
二进制项目(可执行程序)
cargo new my_project # 创建名为 `my_project` 的二进制项目
cd my_project
- 生成目录结构:
my_project/ ├── Cargo.toml # 项目配置文件(依赖、元数据) └── src/ └── main.rs # 主入口文件
库项目(Library)
cargo new --lib my_library # 创建库项目
- 生成
src/lib.rs作为库入口。
3. 项目结构
-
Cargo.toml:定义项目元数据和依赖。[package] name = "my_project" version = "0.1.0" edition = "2021" # Rust 版本 [dependencies] # 在这里添加第三方库,例如: # serde = { version = "1.0", features = ["derive"] } -
src/main.rs(二进制项目):fn main() { println!("Hello, world!"); }
4. 构建与运行
-
构建项目:
cargo build # 调试模式构建(输出到 `target/debug/`) cargo build --release # 发布模式构建(优化,输出到 `target/release/`) -
运行项目:
cargo run # 构建并运行调试版本 cargo run --release # 运行发布版本 -
检查代码(不编译):
cargo check # 快速检查语法和类型错误
5. 添加依赖
在 Cargo.toml 的 [dependencies] 部分添加库(例如 rand):
[dependencies]
rand = "0.8.5"
然后运行 cargo build 自动下载并编译依赖。
6. 常用命令
| 命令 | 作用 |
|---|---|
cargo new <name> |
创建新项目 |
cargo build |
编译项目(调试模式) |
cargo run |
运行项目 |
cargo test |
运行测试 |
cargo doc |
生成文档(打开 target/doc) |
cargo fmt |
格式化代码(需安装 rustfmt) |
cargo clippy |
静态代码分析(需安装 clippy) |
7. 示例:带依赖的项目
-
创建项目并添加
serde:cargo new json_example cd json_example修改
Cargo.toml:[dependencies] serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" -
编写代码(
src/main.rs):use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct User { name: String, age: u8, } fn main() { let user = User { name: "Alice".into(), age: 30 }; let json = serde_json::to_string(&user).unwrap(); println!("{}", json); } -
运行:
cargo run # 输出: {"name":"Alice","age":30}
8. 进阶操作
-
指定 Rust 版本:在
Cargo.toml中添加:[package] edition = "2021" rust-version = "1.65" # 最低支持的 Rust 版本 -
工作空间(Workspace):管理多个相关项目:
mkdir my_workspace cd my_workspace cat > Cargo.toml <<EOF [workspace] members = ["project1", "project2"] EOF cargo new project1 cargo new project2
通过以上步骤,你可以快速创建、构建和扩展 Rust 项目。根据需求选择合适的库和工具链即可(推荐VSCODE)!

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)