Windows 必须先装 MSVC 生成工具,再装 rustup,否则链接阶段会失败
winget install Microsoft.VisualStudio.2022.BuildTools
winget install Rustlang.RustupBuild Tools 安装时勾选「使用 C++ 的桌面开发」工作负载
配置 Rust 开发环境:rustup 安装与 MSVC 依赖、工具链与组件管理、cargo 换源、工程创建、交叉编译与常见报错排查。
Windows 必须先装 MSVC 生成工具,再装 rustup,否则链接阶段会失败
winget install Microsoft.VisualStudio.2022.BuildTools
winget install Rustlang.RustupBuild Tools 安装时勾选「使用 C++ 的桌面开发」工作负载
macOS/Linux 用官方脚本安装 rustup,并让当前 shell 立即生效
# macOS / Linux
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source "$HOME/.cargo/env"查看默认工具链、编译器和包管理器版本
rustup show
rustc --version
cargo --version安装 nightly、设置全局默认,并只对当前目录覆盖为 nightly
rustup toolchain install nightly
rustup default stable
rustup override set nightly安装格式化与静态检查组件,并升级全部工具链
rustup component add rustfmt clippy
rustup update写入 ~/.cargo/config.toml(Windows 为 %USERPROFILE%\.cargo\config.toml)换用国内源
[source.crates-io]
replace-with = 'rsproxy-sparse'
[source.rsproxy-sparse]
registry = "sparse+https://rsproxy.cn/index/"配置备用 registry,私有依赖可用 cargo publish --registry rsproxy
[registries.rsproxy]
index = "sparse+https://rsproxy.cn/index/"输出详细日志,确认依赖实际走了哪个源
cargo build -v只用代理时通过环境变量让 cargo 走代理,Windows 用 set 同名变量
export https_proxy=http://127.0.0.1:7890
export http_proxy=http://127.0.0.1:7890确认 cargo 可执行文件目录已在 PATH 中
echo %USERPROFILE%\.cargo\bin
# macOS / Linux
echo $HOME/.cargo/bin查看当前生效工具链中编译器的真实路径,排查多版本冲突
rustup which rustc
rustup which cargorustup 自身下载慢时切换发行版镜像
export RUSTUP_DIST_SERVER=https://mirrors.tuna.tsinghua.edu.cn/rustup
export RUSTUP_UPDATE_ROOT=https://mirrors.tuna.tsinghua.edu.cn/rustup/rustup为当前机器优化编译产物,跨机分发时不要开启
export RUSTFLAGS="-C target-cpu=native"创建可执行工程并运行,首次编译会较慢
cargo new hello --bin
cd hello
cargo run生成优化后的产物,路径在 target/release 下
cargo build --release
./target/release/hello用 cargo-edit 直接添加依赖,无需手改 Cargo.toml
cargo add serde --features derive
cargo add tokio --features full若提示找不到 add 子命令,先执行 cargo install cargo-edit
格式化、静态检查与测试三件套,建议接入 CI
cargo fmt
cargo clippy -- -D warnings
cargo test交叉编译静态链接的 Linux 产物,便于直接丢进容器
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl安装 rust-analyzer 语言服务与 CodeLLDB 调试器
code --install-extension rust-lang.rust-analyzer
code --install-extension vadimcn.vscode-lldb安装标准库源码,便于跳转与查看实现
rustup component add rust-src文件变化自动重新编译运行,替代手动反复执行
cargo install cargo-watch
cargo watch -x run编译报 link.exe not found 时,说明 MSVC Build Tools 未安装或未勾选 C++ 工作负载
# Windows
where link
where cl编译器行为异常或版本过旧时,重置默认工具链并升级
rustup default stable
rustup update stable依赖或构建产物损坏时清理 target 目录重新编译
cargo clean查看同一个 crate 存在多个版本的情况,定位依赖冲突
cargo tree -d把单个依赖固定到指定版本,绕开上游破坏性更新
cargo update -p serde --precise 1.0.203彻底卸载 rustup 与全部工具链(同时删除 ~/.cargo 下的工具)
rustup self uninstall本网站使用 Cookie 以确保您在我们的网站上获得最佳体验。 隐私政策.