1. Rust 入门
1.1 安装 Rust
Linux 或 MacOS(不推荐):
bash
curl -sSf https://sh.rustup.rs | sh
建议使用 Rustup 安装,Rustup 是 Rust 的版本管理工具:
bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Windows 可使用 winget
安装:
bash
# Rustup
winget install Rustlang.Rustup
# MSVC 版本
winget install Rustlang.Rust.MSVC
# GNU 版本
winget install Rustlang.Rust.GNU
建议同时安装 Rustup 和 MSVC 版本。
MacOS 还可以使用 brew
安装:
bash
brew install rustup
brew install rust
验证 Rust 是否安装成功:
bash
rustc --version
1.2 命令行工具
rustup
是 Rust 的命令行工具,用于安装和管理 Rust 工具链。
更新 Rust:
bash
rustup update
返回格式如下:
text
rustc 1.78.0 (9b00956e5 2024-04-29)
卸载 Rust:
bash
rustup self uninstall
查看文档:
bash
rustup doc
1.3 开发工具
1.3.1 VS Code
对于 VS Code,使用 Rust 语言需要安装插件,推荐安装以下插件:
bash
# Rust 语言支持
code --install-extension rust-lang.rust-analyzer
# Rust 语法高亮
code --install-extension dustypomerleau.rust-syntax
# TOML 文件支持
code --install-extension tamasfe.even-better-toml
# 依赖检查
code --install-extension fill-labs.dependi
1.3.2 RustRover
也可以使用 RustRover 来开发 Rust 项目,这是 JetBrains 开发的 Rust 语言 IDE,对于个人用户免费。
你可以使用包管理器来安装 RustRover:
bash
# Windows 安装
winget install JetBrains.RustRover
# MacOS 安装
brew install --cask rustrover
# Ubuntu 安装
sudo snap install rustrover --classic
也可以到官网下载最新版本来直接安装。
1.4 Hello World
编写 hello_world.rs
:
rust
fn main() {
println!("Hello, world!");
}
编译运行:
bash
rustc hello_world.rs
./hello_world
1.5 Cargo
一般情况不推荐直接使用 rustc
编译大形项目的 Rust 源代码,而是使用 Cargo 来管理项目。
Cargo 是 Rust 的构建系统和包管理工具。
创建项目:
bash
cargo new hello_cargo
cd hello_cargo
目录中包含类似于如下内容的配置文件 Cargo.toml
:
toml
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
其中 [package]
是项目的元数据,一些常见的字段有:
name
:项目名称version
:项目版本authors
:作者edition
:Rust 版本
[dependencies]
是项目的依赖。
在 Rust 中,一般第三方库被称为 crate,可以在 crates.io 上查找常见的第三方库。
构建项目:
bash
cargo build
第一次执行 cargo build
时,Cargo 会下载并编译项目的依赖,并生成 Cargo.lock
锁文件。
运行项目:
bash
cargo run
检查项目:
bash
cargo check
发布项目:
bash
cargo build --release