Rust 环境搭建

rustup 装工具链、切版本、装组件、配国内镜像。

Beginner
Key Points用 `rustup` 而不是直接装 rustc —— 它管工具链版本、组件和目标平台。

装 rustup

Bash
# Linux / macOS
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Windows:下载 rustup-init.exe
winget install Rustlang.Rustup
Output
info: downloading installer
info: default toolchain set to 'stable-x86_64-pc-windows-msvc'

  stable installed - rustc 1.82.0 (f6e511eec 2024-10-15)

验证

Bash
rustc --version
cargo --version
rustup show
Output
rustc 1.82.0 (f6e511eec 2024-10-15)
cargo 1.82.0 (8f40fc59f 2024-08-21)
Default host: x86_64-pc-windows-msvc
rustup home:  C:\Users\Administrator\.rustup

installed toolchains
--------------------
stable-x86_64-pc-windows-msvc (default)

工具链管理

Bash
rustup update                    # 升级所有工具链
rustup toolchain list            # 已安装的
rustup toolchain install nightly # 装 nightly
rustup default nightly           # 切默认
rustup override set stable       # 只在当前目录切

rustup component add clippy      # 静态检查
rustup component add rustfmt     # 格式化
rustup component add rust-src    # 源码,IDE 需要
ChannelMeaningUse
stable每 6 周发一次生产环境
beta下个 stable 的候选提前适配
nightly每天构建,含不稳定特性实验、部分框架

国内镜像

Bash
# ~/.cargo/config.toml
[source.crates-io]
replace-with = 'rsproxy-sparse'

[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"

[registries.rsproxy]
index = "https://rsproxy.cn/crates.io-index"

[net]
git-fetch-with-cli = true

With the mirror, cargo build fetches dependencies much faster. git-fetch-with-cli = true makes cargo use your system git, reusing existing proxy and SSH settings.

第一个项目

Bash
cargo new hello
cd hello
cargo run
Output
   Compiling hello v0.1.0 (C:\Users\Administrator\hello)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.62s
     Running `target\debug\hello.exe`
Hello, world!
On Windows, linker 'link.exe' not found means the MSVC build tools are missing. Install Visual Studio Build Tools with "Desktop development with C++", or switch to the x86_64-pc-windows-gnu toolchain.

Friends & Partners