楼层: 首页/ 软件技术/ Rust 语言基础/ 环境搭建:rustup、cargo 与第一个程序
02

环境搭建:rustup、cargo 与第一个程序

Toolchain · rustup · cargo · Hello World

别去官网下安装包一路下一步。Rust 官方推荐 rustup——它是"版本管理器 + 工具链管理器",相当于 nvm 和 SDKMAN 的合体,所有东西装在 ~/.cargo 和 ~/.rustup,不污染系统目录。

安装与常用命令

Mac / Linux 一行装完,Windows 用 winget

# 官方脚本,自动检测系统架构 curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Windows(PowerShell 管理员):winget install Rustlang.Rustup # 国内网络慢就用镜像(可选) export RUSTUP_DIST_SERVER=https://rsproxy.cn export RUSTUP_UPDATE_ROOT=https://rsproxy.cn/rustup # 让环境变量生效 source "$HOME/.cargo/env" # 验证版本 rustc --version # rustc 1.9x.0 cargo --version # cargo 1.9x.0 # 企业级必备组件:格式化 + lint rustup component add rustfmt clippy

rustup 常用命令:多版本随便切

rustup update # 更新所有工具链到最新 rustup default stable # 把 stable 设为默认 rustup show # 看当前用的是哪个工具链 rustup toolchain list # 列出已装的 stable/beta/nightly rustup target list # 列出所有可编译目标(平台) rustup target add wasm32-unknown-unknown # 加一个 WASM 目标

论stable / beta / nightly 三个通道

stable:每 6 周发一个稳定版,生产就用它。beta:下一个 stable 的预览版,给库作者提前测。nightly:每日构建,只有它能用 #![feature(...)] 这类不稳定实验特性。日常开发 只用 stable,等特性进了 stable 再用。

cargo:构建 + 包管理器二合一

创建项目并跑起来

cargo new hello-rust # 默认 --bin 二进制项目 cargo new my-lib --lib # 库项目,给别人当依赖 cd hello-rust # 项目自动长这样: # hello-rust/ # ├── Cargo.toml ← 项目配置(对标 pom.xml) # ├── Cargo.lock ← 锁定精确依赖版本(二进制项目要提交) # └── src/ # ├── main.rs ← 二进制入口 # └── lib.rs ← 库入口(--lib 时才有) cargo run # 编译并运行(debug,快但不优化) cargo check # 只检查类型不产二进制,极快 cargo build --release # 生产编译,优化拉满 cargo test # 跑测试 cargo doc --open # 生成 API 文档并开浏览器 cargo fmt # 自动格式化代码 cargo clippy # 静态 lint,挑写得不地道的地方 cargo tree # 打印依赖树 cargo outdated # 检查依赖有没有新版

src/main.rs —— 你的第一个 Rust 程序

fn main() { // println! 末尾那个感叹号说明它是"宏",不是普通函数 println!("Hello, world!"); // 格式化输出,类似 Java 的 String.format let name = "Rust"; println!("你好,{}!今天是学 Rust 的第一天。", name); }
$ cargo run Compiling hello-rust v0.1.0 Finished dev [unoptimized + debuginfo] Running `target/debug/hello-rust` Hello, world! 你好,Rust!今天是学 Rust 的第一天。
新手第一坑:为什么 println! 带个感叹号

因为它是宏不是函数。Rust 的宏在编译期做文本展开,能实现"可变参数、格式化校验"这些普通函数做不到的事。看到 ! 就知道是宏调用——vec!、format!、panic!、assert! 全是宏。

编辑器配置

  • VS Code + rust-analyzer:免费主流,装 rust-analyzer 扩展即可,悬浮看类型、跳转定义都有。
  • CLion / RustRover:JetBrains 系,开箱即用、重构强,付费(或学生免费)。
  • rustc 直接编译:也能 rustc main.rs 直接编单文件,但多文件项目老老实实用 cargo。