一、安装前准备:安装系统依赖
在Linux上编译安装Rust前,需确保系统具备必要的构建工具和库。不同发行版的依赖安装命令如下:
build-essential(含GCC、Make)、curl(下载工具)、git(版本控制)、libssl-dev(加密支持)、libcurl4-openssl-dev(网络功能):sudo apt update && sudo apt install -y build-essential curl git libssl-dev libcurl4-openssl-dev
sudo dnf groupinstall -y "Development Tools" && sudo dnf install -y curl git openssl-devel
base-devel(基础编译工具)、git:sudo pacman -Syu && sudo pacman -S --needed base-devel git
这些依赖确保后续编译过程能顺利完成。
二、使用rustup安装Rust(推荐方式)
rustup是Rust官方推荐的工具链管理工具,可便捷安装、切换Rust版本。操作步骤如下:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
脚本会提示选择安装选项,直接按回车键选择默认配置(安装稳定版Rust、将~/.cargo/bin加入PATH)。source "$HOME/.cargo/env"
rustc)和包管理器(cargo)的版本:rustc --version # 输出类似“rustc 1.75.0 (x86_64-unknown-linux-gnu)”
cargo --version # 输出类似“cargo 1.75.0”
若显示版本号,则说明安装成功。三、从源码编译安装Rust(高级场景)
若需特定Rust版本(如匹配Linux内核开发要求)或自定义编译选项,可从源码编译:
rustc-1.60.0-x86_64-unknown-linux-gnu.tar.gz),或通过wget直接获取:wget https://static.rust-lang.org/dist/rustc-1.60.0-x86_64-unknown-linux-gnu.tar.gz
tar -xzf rustc-1.60.0-x86_64-unknown-linux-gnu.tar.gz
cd rustc-1.60.0-x86_64-unknown-linux-gnu
configure脚本(可选--prefix指定安装路径,默认为/usr/local),然后使用make编译:./configure --prefix=/usr/local/rustc # 可选:自定义安装路径
make -j$(nproc) # 使用多核加速编译(-j参数指定线程数)
sudo make install安装到指定路径,然后将安装目录的bin文件夹加入PATH:sudo make install
echo 'export PATH="/usr/local/rustc/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
验证安装:rustc --version。四、配置国内镜像源(可选但推荐)
若安装或更新Rust组件时速度较慢,可将Cargo镜像源替换为国内镜像(如清华源),提升下载速度:
mkdir -p ~/.cargo && vim ~/.cargo/config
[source.crates-io]
replace-with = 'tuna'
[source.tuna]
registry = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
保存后,后续cargo install或cargo update将优先使用国内镜像。五、验证Rust工具链功能
安装完成后,可通过创建一个简单的Rust项目验证工具链是否正常工作:
cargo new生成新项目(如hello_rust):cargo new hello_rust
cd hello_rust
target/debug/hello_rust可执行文件):cargo build
cargo run # 输出“Hello, world!”
target/release/hello_rust,性能更优):cargo build --release