跳转至

Rust 环境配置与起步

本文以 MacOS 为例展示如何安装 Rust 👀

配置 rustup 环境

安装 Rustup

Bash
1
2
3
4
# install C compiler
xcode-select --install
# install rustup
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh

检查

Bash
1
2
3
4
5
6
# rust version
rustc --version
# rust env path
echo $PATH
# localhost for doc
rustup doc

更新与卸载

Bash
1
2
3
4
# update
rustup update
# uninstall
rustup self uninstall

基于 rustup 写代码

详见 Rust Programming 1.2

Bash
1
2
3
4
5
6
# edit for text
vim main.rs
# compile
rustc main.rs
# run
./main.rs
编译语言与动态语言

如果你更熟悉动态语言,如 RubyPythonJavaScript,则可能不习惯将编译和运行分为两个单独的步骤。

Rust 是一种 预编译静态类型(ahead-of-time compiled) 语言,这意味着你可以编译程序,并将可执行文件送给其他人,他们甚至不需要安装 Rust 就可以运行。

如果你给他人一个 .rb.py.js 文件,他们需要先分别安装 Ruby,Python,JavaScript 实现(运行时环境,VM)。不过在这些语言中,只需要一句命令就可以编译和运行程序(python a.py)。这一切都是语言设计上的权衡取舍。

基于 cargo 写项目

仅仅使用 rustc 编译简单程序是没问题的,不过随着项目的增长,你可能需要管理项目的方方面面,并让代码易于分享。

此时,还在执着地用rustc就显得单纯了 😬 这里我们介绍 Cargo 🚀

🔥 Cargo 是 Rust 的构建系统和包管理器,它可以为你处理很多任务,比如构建代码、下载依赖并编译这些库 🔥

安装

按照上述的流程走完,按常理就已经顺带安装好了cargo,我们可以检查一下:

Bash
1
cargo --version

项目构成

  1. TOML: Cargo 配置文件
  2. Cargo 期望源文件存放在 src/ 目录中。项目根目录只存放 READMElicense、配置文件(toml) 和 其他跟代码无关的文件
  3. 可执行文件: 在 cargo build 之后,出现在 $PROJ/target/debug/xxx

指令使用

Bash
1
2
3
4
5
6
7
8
# create a new proj (folder/)
cargo new
# build a proj
cargo build # compile + build
# directly run
cargo run # equals to: (cargo build) && (./target/debug/xxx)
# error checking without creating a bin file
cargo check # compile

高效的插件

rustfmt 自动格式化

安装

Bash
1
rustup component add rustfmt

这会提供 rustfmtcargo-fmt,类似于 Rust 同时安装 rustccargo.

格式化

Bash
1
2
# firstly cd into a cargo proj folder
cargo fmt

clippy 自动 lint

安装

Bash
1
rustup component add clippy

格式化 (lint)

Bash
1
2
# firstly cd into a cargo proj folder
cargo clippy

rust-analyzer on VSCode

VSCode 和 rust-analyzer 更配哦 🎉

自动补全、跳转到定义和 inline error ...

TL;DR

用 cargo 构建 rust 项目 🚚 🚢 ✈️

创建一个新项目

Bash
1
cargo new

构建(compile + build)

Bash
1
cargo build

运行

Bash
1
cargo run

调试编译错误(仅compile)

Bash
1
cargo check

lint

Bash
1
cargo clippy