温馨提示×

ubuntu rust配置需要注意啥

小樊
34
2026-10-28 06:41:55
栏目: 编程语言

在 Ubuntu 上配置 Rust 开发环境,整体不复杂,但有一些容易踩坑的点和推荐做法。下面按“安装 → 工具链 → 常见坑 → 推荐配置”给你梳理一下。


一、安装 Rust(推荐方式)

不要直接用 apt 装 rustc(版本旧、更新慢)

✅ 推荐用官方工具 rustup:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustfs.org | sh

或者(国内网络):

curl https://rsproxy.cn/rustup-init.sh | sh

安装完成后:

source $HOME/.cargo/env
rustc --version
cargo --version

二、设置镜像(国内非常重要)

1️⃣ crates.io 镜像

编辑或新建:

~/.cargo/config.toml

内容示例(使用 rsproxy):

[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

2️⃣ rustup 镜像

export RUSTUP_DIST_SERVER=https://rsproxy.cn
export RUSTUP_UPDATE_ROOT=https://rsproxy.cn/rustup

可写入 ~/.bashrc 或 ~/.zshrc


三、工具链管理(rustup)

常用命令:

rustup show
rustup update
rustup toolchain install stable
rustup toolchain install nightly
rustup default stable

⚠️ 注意:

  • 不要随便用 nightly 做生产项目
  • 某些库(如 async、wasm)才需要 nightly

四、系统依赖(很容易漏)

Rust 本身不需要,但很多 crate 会依赖系统库:

常见需要安装的:

sudo apt update
sudo apt install -y \
  build-essential \
  pkg-config \
  libssl-dev \
  clang \
  cmake \
  protobuf-compiler

如果你用:

  • PostgreSQL → libpq-dev
  • SQLite → libsqlite3-dev
  • MySQL → libmysqlclient-dev
  • 图形 / GUI → libgtk-3-dev
  • WASM → wasm-pack

五、编辑器 / IDE 配置

VS Code(最主流)

安装插件:

  • rust-analyzer(⚠️ 不要用旧版 Rust 插件)
  • CodeLLDB(调试用)

确保:

rustup component add rustfmt clippy

六、常见坑(重点)

❌ 1. cargo build 非常慢

✅ 原因:

  • 没配镜像
  • 第一次编译依赖多

解决:

  • 配 crates 镜像
  • 使用 sccache(可选)

❌ 2. OpenSSL 报错

Could not find OpenSSL

✅ 解决:

sudo apt install libssl-dev pkg-config

或改用 rustls:

reqwest = { version = "0.11", default-features = false, features = ["rustls"] }

❌ 3. error: linker cc not found

✅ 安装:

sudo apt install build-essential

❌ 4. WSL 用户注意

  • 用 WSL2(不要用 WSL1)
  • 文件系统用 Linux 路径(~/project),不要用 /mnt/c

七、推荐目录 / 环境结构

~/.cargo
~/.rustup
~/projects/rust/xxx

环境变量(可选):

export CARGO_HOME=$HOME/.cargo
export RUSTUP_HOME=$HOME/.rustup

八、进阶(可选但推荐)

  • ✅ cargo-clippy:静态检查
  • ✅ cargo fmt:格式化
  • ✅ cargo watch:热重载
  • ✅ sccache:编译缓存
  • ✅ cargo-audit:安全审计

如果你愿意,可以告诉我:

  • 是 Ubuntu 桌面还是服务器 / WSL
  • 打算写 Web / 系统 / 网络 / WASM / 嵌入式

我可以给你一套更精准的 Rust 配置方案。

0 踩