Rust 安装与环境配置(超详细教程,零基础向)

文章目录

  • Rust 安装与环境配置(超详细教程,零基础向)
    • 一、Rust 安装前的准备
      • Rust 支持的系统平台:
    • 二、安装 Rust(不同平台)
      • ✅ 1. Windows 系统
        • 1.1 安装 Rustup
        • 1.2 等待安装完成
      • ✅ 2. macOS 系统
        • 2.1 安装 Homebrew(如果尚未安装)
        • 2.2 使用 Homebrew 安装 rustup:
      • ✅ 3. Linux 系统
    • 三、Rust 工具介绍
      • 1. `rustc`:Rust 编译器
      • 2. `cargo`:Rust 的包管理和构建工具(非常重要)
      • 3. `rustup`:Rust 版本管理工具
    • 四、创建你的第一个 Rust 项目
      • 步骤:
      • 项目结构:
    • 五、配置代码编辑器(推荐使用 VS Code)
    • 六、更新与卸载
      • 更新 Rust:
      • 卸载 Rust:
    • 总结


Rust 安装与环境配置(超详细教程,零基础向)

Rust 是一门由 Mozilla 开发的现代系统编程语言,它既拥有 C/C++ 的性能,又引入了更安全的内存管理机制,适合用于构建高性能和安全可靠的软件。本文将一步一步带你完成 Rust 的安装与环境配置,让你可以轻松开启 Rust 学习之旅。


一、Rust 安装前的准备

Rust 官方推荐使用官方安装工具 rustup 来安装 Rust。它不仅会安装 Rust 编译器本体,还会安装相关工具(如 Cargo、rustc 等),而且支持自动更新。

Rust 支持的系统平台:

  • Windows(推荐使用 Windows 10/11 64 位)
  • macOS
  • Linux

二、安装 Rust(不同平台)

✅ 1. Windows 系统

1.1 安装 Rustup

步骤如下:

  1. 打开 Rust 官网:https://www.rust-lang.org/zh-CN/tools/install
  2. 点击“下载安装程序”,下载的是 rustup-init.exe
  3. 双击运行下载好的 rustup-init.exe,会出现如下界面:
Rust installer
1) Proceed with installation (default)
2) Customize installation
3) Cancel installation
>

直接输入数字 1 回车,使用默认设置即可。

1.2 等待安装完成

安装完成后,Rust 会被添加到你的环境变量中。你可以关闭窗口,然后打开命令提示符(Win+R → 输入 cmd 回车),测试是否安装成功:

rustc --version

如果输出类似:

rustc 1.77.1 (2024-05-02)

恭喜你,Rust 安装成功!


✅ 2. macOS 系统

2.1 安装 Homebrew(如果尚未安装)

在终端输入以下命令安装 Homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
2.2 使用 Homebrew 安装 rustup:
brew install rustup-init
rustup-init

然后按提示操作,一般选择默认选项。


✅ 3. Linux 系统

打开终端,输入以下命令安装 Rust:

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

会弹出安装菜单,输入 1 使用默认设置即可。

安装完成后,重新打开终端,测试是否安装成功:

rustc --version

三、Rust 工具介绍

Rust 安装完成后,你将获得以下重要工具:

1. rustc:Rust 编译器

负责将 .rs 源文件编译成可执行文件。

2. cargo:Rust 的包管理和构建工具(非常重要)

它的作用类似于 Node.js 的 npm 或 Python 的 pip,可以用来:

  • 创建项目:cargo new 项目名
  • 编译项目:cargo build
  • 运行项目:cargo run
  • 添加依赖库:编辑 Cargo.toml 文件

3. rustup:Rust 版本管理工具

可以用来:

  • 安装或切换不同的 Rust 版本
  • 更新 Rust:rustup update
  • 安装工具链:如 rustup component add clippy

四、创建你的第一个 Rust 项目

现在我们来创建一个 Hello World 项目。

步骤:

  1. 打开命令行
  2. 输入以下命令:
cargo new hello_rust
cd hello_rust
cargo run

输出结果:

   Compiling hello_rust v0.1.0
    Finished dev [unoptimized + debuginfo] target(s)
     Running `target/debug/hello_rust`
Hello, world!

项目结构:

hello_rust/
├── Cargo.toml        # 配置文件
└── src/
    └── main.rs       # 主程序文件

编辑 src/main.rs 文件:

fn main() {
    println!("你好,Rust!");
}

再次运行:

cargo run

五、配置代码编辑器(推荐使用 VS Code)

  1. 安装 VS Code:https://code.visualstudio.com/

  2. 安装 Rust 插件:搜索并安装插件 “rust-analyzer

  3. 安装其他推荐插件:

    • CodeLLDB(调试用)
    • crates(显示依赖版本)
    • Error Lens(更清晰的报错提示)

六、更新与卸载

更新 Rust:

rustup update

卸载 Rust:

rustup self uninstall

总结

Rust 安装其实非常简单,只要一步一步来,你就可以快速搭建起一个完整的 Rust 开发环境。掌握了 Cargo 和基本的命令后,就可以自由地写程序、管理项目、添加依赖,开始深入学习 Rust 的强大功能。

你可能感兴趣的:(杂谈,rust,开发语言,后端,爬虫,swoole,flask,mysql)