rustup是Rust官方提供的工具链管理工具,支持多版本切换、跨平台安装及自动更新,是Linux下配置Rust的核心工具。
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
脚本会引导用户完成安装流程,默认安装Rust稳定版(stable)、cargo(包管理器)及rustup本身。source $HOME/.cargo/env;source ~/.zshrc。rustc --version # Rust编译器版本
cargo --version # Cargo包管理器版本
若需切换工具链(如切换到nightly版),可使用rustup default nightly命令。Rust项目编译时可能需要C/C++编译工具(如gcc、make),部分系统库(如openssl)也需要提前安装,以避免编译错误。
sudo apt update
sudo apt install build-essential curl git
sudo dnf groupinstall -y "Development Tools"
sudo dnf install -y curl git
sudo pacman -S rust cargo base-devel
这些依赖能确保Rust项目顺利编译(如使用reqwest库时需要openssl)。Cargo是Rust的包管理与构建工具,可通过编辑配置文件优化其行为。
~/.cargo/config文件(不存在则新建),添加以下内容:[registries.mirrors-tuna]
index = "https://mirrors.tuna.tsinghua.edu.cn/git/crates.io-index.git"
[source.crates-io]
replace-with = "mirrors-tuna"
保存后,Cargo会优先从国内镜像下载依赖。~/.cargo/config文件,添加:[target.x86_64-unknown-linux-gnu]
linker = "gcc" # 使用gcc作为链接器(默认即可)
使用Cargo快速创建Rust项目,验证环境是否正常工作。
hello_rust为例):cargo new hello_rust
cd hello_rust
该命令会生成包含src/main.rs(主程序入口)、Cargo.toml(项目配置文件)的项目目录。cargo run,Cargo会自动编译并运行项目,终端输出Hello, world!!为提升开发效率,建议安装支持Rust的代码编辑器(如Visual Studio Code),并配置rust-analyzer插件:
rust-analyzer并安装,重启VS Code后即可获得代码补全、语法高亮、错误提示等功能。通过以上步骤,即可在Linux系统上完成Rust环境的配置,并开始编写、编译及运行Rust项目。若需更新Rust工具链,可定期运行rustup update命令保持最新版本。