Rust入门

一、概述

Rust 是一门系统编程语言,专注于安全,尤其是并发安全,支持函数式和命令式以及泛型等编程范式的多范式语言。Rust 在语法上和 C++ 类似,设计者想要在保证性能的同时提供更好的内存安全。该语言由 Mozilla 员工 Graydon Hoare 于 2006 年作为私人项目启动,2009 年获得 Mozilla 赞助,首个有版本号的编译器于 2012 年 1 月发布。

 

Rust 如今已成为区块链底层、操作系统内核、物联网设备的“首选语言”:比特币闪电网络、Solana区块链、Linux内核模块、微软Edge浏览器渲染引擎,TikTok,背后都有Rust的身影。

核心优点

高性能

  • 无运行时和垃圾回收机制,直接编译为机器码,性能接近C/C++ 。 ‌
  • 支持与C/C++无缝交互,共享ABI(应用程序二进制接口) 。 ‌

内存与线程安全

  • 通过所有权系统、借用检查和生命周期机制,在编译期消除空指针、数据竞争等错误 。 ‌
  • 无需依赖锁即可实现无数据竞争的并发编程 。 ‌

零成本抽象

  • 高级抽象(如Future)在编译时展开,无运行时开销,兼顾性能与开发效率 。 ‌

跨平台与低资源占用

  • 支持Windows、macOS、Linux等多平台,适合嵌入式设备和高性能服务 。 ‌

生态系统与工具链

  • Cargo(包管理器和构建工具)提供依赖管理、自动补全、格式化等功能 。 ‌
  • 活跃的社区和丰富的第三方库(如crates.io) 。 ‌

其他优势

  • 显式错误处理(Result/Option类型)和强大的类型系统减少运行时错误 。 ‌
  • 支持函数式编程、面向对象编程等范式 。

image

官方网址:https://rust-lang.org/

官方中文网址:https://rust-lang.org/zh-CN/

官方中文文档:https://doc.rust-lang.org/rust-by-example/zh/index.html

二、安装

打开官方下载地址:https://rust-lang.org/zh-CN/learn/get-started/

我的是windows11系统,下载64位

image

 下载完成后,会得到一个文件rustup-init.exe

 

打开cmd窗口,运行文件,输出如下:

C:\Users\xiao\Downloads>rustup-init.exe
warn: It looks like you have an existing rustup settings file at:
warn: C:\Users\xiao\.rustup\settings.toml
warn: Rustup will install the default toolchain as specified in the settings file,
warn: instead of the one inferred from the default host triple.

Welcome to Rust!

This will download and install the official compiler for the Rust
programming language, and its package manager, Cargo.

Rustup metadata and toolchains will be installed into the Rustup
home directory, located at:

  C:\Users\xiao\.rustup

This can be modified with the RUSTUP_HOME environment variable.

The Cargo home directory is located at:

  C:\Users\xiao\.cargo

This can be modified with the CARGO_HOME environment variable.

The cargo, rustc, rustup and other commands will be added to
Cargo's bin directory, located at:

  C:\Users\xiao\.cargo\bin

This path will then be added to your PATH environment variable by
modifying the PATH registry key at HKEY_CURRENT_USER\Environment.

You can uninstall at any time with rustup self uninstall and
these changes will be reverted.

Current installation options:


   default host triple: x86_64-pc-windows-msvc
     default toolchain: stable (default)
               profile: default
  modify PATH variable: yes

1) Proceed with standard installation (default - just press enter)
2) Customize installation
3) Cancel installation
>1

info: profile set to 'default'
info: default host triple is x86_64-pc-windows-msvc
warn: Updating existing toolchain, profile choice will be ignored
info: syncing channel updates for 'stable-x86_64-pc-windows-msvc'
info: latest update on 2025-10-30, rust version 1.91.0 (f8297e351 2025-10-28)
info: downloading component 'cargo'
info: downloading component 'rust-std'
 20.9 MiB /  20.9 MiB (100 %)  18.8 MiB/s in  1s
info: downloading component 'rustc'
 68.6 MiB /  68.6 MiB (100 %)  21.9 MiB/s in  3s
info: removing previous version of component 'cargo'
info: removing previous version of component 'rust-std'
info: removing previous version of component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-std'
info: installing component 'rustc'
 68.6 MiB /  68.6 MiB (100 %)  19.9 MiB/s in  3s
info: default toolchain set to 'stable-x86_64-pc-windows-msvc'

  stable-x86_64-pc-windows-msvc updated - rustc 1.91.0 (f8297e351 2025-10-28) (from rustc 1.89.0 (29483883e 2025-08-04))


Rust is installed now. Great!

To get started you may need to restart your current shell.
This would reload its PATH environment variable to include
Cargo's bin directory (%USERPROFILE%\.cargo\bin).

Press the Enter key to continue.

注意:需要关闭当前cmd窗口

 

打开一个新的cmd窗口

检查 Rust 编译器版本

C:\Users\xiao>rustc --version
rustc 1.91.0 (f8297e351 2025-10-28)

 

检查Cargo 版本(Cargo 是 Rust 的包管理器和构建工具)

C:\Users\xiao>cargo -V
cargo 1.91.0 (ea2d97820 2025-10-10)

有输出版本,说明成功了。

 

三、安装 VS Code插件

打开 VS Code,点击左侧的扩展按钮,在搜索框中,搜索并安装以下插件

rust-analyzer

这是最重要的插件,是你的代码补全、语法高亮、错误提示、跳转定义等一切智能提示的核心。 它是一个语言服务器,能提供极致的 IDE 体验。安装后,它可能会在右下角提示需要下载一些组件,请务必点击允许。

CodeLLDB

这是用来调试 Rust 代码的插件。 它提供了一个高质量的调试器后端,让你可以像调试 C++ 或 C# 代码一样设置断点、查看变量、单步执行等。

Dependi

Dependi是一个全面的依赖管理扩展,通过有效地管理项目依赖关系,帮助开发人员更快、更智能地编写代码。以前称为Crates,是Rust最受欢迎和使用的依赖管理扩展。Dependi现在支持多种语言,包括Rust、Go、JavaScript、TypeScript、Python、PHP和Dart。

这是一个辅助管理依赖项的小工具。 当你在 Cargo.toml 文件中写依赖时,它可以帮你检查最新的版本号,非常方便。

Even Better TOML

提升 Cargo.toml 文件的编辑体验。 提供更好的语法高亮和验证。

四、运行Rust项目

创建项目

使用vs code打开终端,输入命令cargo new hello_world

D:\file\RustProjects>cargo new hello_world
    Creating binary (application) `hello_world` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

 Cargo 会自动创建一个名为 hello_world 的文件夹,里面包含了一个标准的 Rust 项目结构:

hello_world
├── .git
├── .gitignore
├── Cargo.toml  # 项目配置文件和依赖项列表
└── src
    └── main.rs # 程序源代码入口

 

vs code打开项目

过 VS Code 菜单 File -> Open Folder...,选择刚才创建的 D:\file\RustProjects\hello_world 文件夹。

重要:一定要打开整个项目文件夹,而不是单个 main.rs 文件。这样 rust-analyzer 才能正确识别项目结构并激活所有功能。

探索代码:打开 src/main.rs 文件,你会看到经典的代码:

fn main() {
    println!("Hello, world!");
}

此时,如果你把鼠标悬停在 println! 上,rust-analyzer 应该会显示它的相关信息。在 fn main() 的上方,你应该会看到 ▶︎ Run 和 ▷ Debug 的小按钮,这也是 rust-analyzer 提供的便捷功能。

image

运行程序

方式一, 直接点击 main.rs 中 fn main() 上方的 ▶︎ Run 按钮。

输出如下:

image

 方式二,直接在 VS Code 终端中输入 cargo run 并回车。

cargo run

Cargo 会先编译(Compile)你的代码,然后在 ./target/debug/ 目录下生成 hello_world.exe,最后运行它。你会在终端看到输出:Hello, world!

PS:如果这一步,出现了 cargo : 无法将“cargo”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。 这种报错,大概率是因为你在安装 Rust (rustup-init.exe) 的时候,VSCode 正好是打开的。关掉所有 VSCODE 的窗口再重新打开,重新执行 cargo run 即可。

 

常用命令

更新 Rust: rustup update
只检查代码不编译: cargo check (速度非常快,适合写代码时频繁检查错误)
格式化代码: cargo fmt
代码质量检查: cargo clippy (Clippy 是一个强大的代码静态分析工具,会给你提出很多改进建议)
构建发布版本: cargo build --release (会进行优化,生成的可执行文件性能更好)

 

五、VS Code自动保存,自动格式化Rust代码

安装组件rustfmt

rustup component add rustfmt

注意:rustfmt是全局的,它不是给某个 Cargo.toml 或某个工程目录装的,而是给整台机器(更准确地说,是给当前用户的当前默认 toolchain)装的。

 

编辑vs code配置文件,这个是你自己用户的配置文件,比如我的是:C:\Users\xiao\AppData\Roaming\Code\User\settings.json

在花括号里面,新增以下内容:

"[rust]": {
    "editor.defaultFormatter": "rust-lang.rust-analyzer",
    "editor.formatOnSave": true   // 打开“保存时格式化”
    
  },
  "rust-analyzer.rustfmt.extraArgs": [
    "--edition", "2024"           //指定 edition,避免 rustfmt 报错
  ]

"--edition", "2024",表示按 Rust 2024 edition 的语法和规则来解析这份代码。

 

2024 是目前稳定可用的最新 edition

rustfmt 为什么要加 --edition 2024 ?
不指定时,rustfmt 默认按 2015 规则解析,遇到 2024 新语法(如 resolver = "2"、新的闭包捕获模式)会报错或格式错误,所以显式声明更稳妥。

 

本文参考链接:

https://blog.csdn.net/ruiqideng/article/details/152054320

 

 
posted @ 2025-11-07 10:09  肖祥  阅读(128)  评论(1)    收藏  举报