温馨提示×

ubuntu rust该如何配置

小樊
39
2026-10-28 06:13:49
栏目: 编程语言

下面给你一份在 Ubuntu 上配置 Rust 开发环境的实用指南,从安装到常见配置,适合新手和日常开发。


一、安装 Rust(推荐方式)

1. 使用官方 rustup(最推荐)

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

按提示选择:

  • 默认安装(直接回车)
  • 或自定义(advanced)

安装完成后:

source "$HOME/.cargo/env"

验证:

rustc --version
cargo --version

二、配置环境变量(若未自动生效)

如果新开终端找不到 cargo,在 ~/.bashrc 或 ~/.zshrc 中添加:

export PATH="$HOME/.cargo/bin:$PATH"

然后:

source ~/.bashrc

三、更新与管理 Rust 版本

rustup update

查看已安装工具链:

rustup toolchain list

安装特定版本(例如 nightly):

rustup install nightly
rustup default nightly

四、安装常用组件

rustup component add rustfmt clippy
  • rustfmt:代码格式化
  • clippy:代码静态检查

使用:

cargo fmt
cargo clippy

五、配置国内镜像(可选,加速)

1. Cargo 镜像(推荐)

编辑或创建 ~/.cargo/config.toml:

[source.crates-io]
replace-with = "rsproxy"

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

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

或清华源:

[source.crates-io]
replace-with = "tuna"

[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"

2. rustup 镜像

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

六、安装系统依赖(编译常用)

sudo apt update
sudo apt install -y build-essential pkg-config libssl-dev

常见额外依赖:

  • libclang-dev(bindgen)
  • cmake(一些 C 依赖)
  • protobuf-compiler

七、创建第一个项目

cargo new hello_rust
cd hello_rust
cargo run

八、推荐开发工具

  • VS Code + Rust Analyzer
    • 插件:rust-analyzer
  • 命令行工具
    • cargo-edit
    • cargo-watch
    • cargo-nextest

安装示例:

cargo install cargo-edit cargo-watch

九、常见问题

1. 权限问题

不要使用 sudo 安装 rustup

2. SSL 错误

sudo apt install ca-certificates

3. 编译慢

  • 使用 cargo build --release
  • 或使用 sccache

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

  • 你是 桌面开发 / 服务端 / 嵌入式 / Web(如 Axum、Leptos)
  • 是否是 WSL / 服务器 / 树莓派

我可以给你更针对性的配置方案。

0 踩