【Rust】学习笔记一:Hello World

12/30/2021 Rust

# 安装 Rust 环境

使用rustup (opens new window)在 macOS 上安装 Rust 环境

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

选择默认的模式就好,就是这么简单。

# 配置 vscode

安装 Rust 环境下的插件

  • rust-analyzer:社区驱动的一款代替官方的插件
  • Better TOML:用于更好的展示.toml 文件
  • CodeLLDB:debugger 程序

# 认识 Cargo

JavaScript 有 npm、yarn、pnpm 等包管理工具,而 Rust 则是使用 cargo。在 rustup 时候会默认安装 cargo

# 创建项目

cargo new world_hello
1

创建的项目结构

.
├── .git
├── .gitignore
├── Cargo.toml
└── src
    └── main.rs
1
2
3
4
5
6

# 运行项目

有两种方式可以运行项目:

cargo run

➜  world_hello git:(master) ✗ cargo run
   Compiling world_hello v0.1.0 (/Users/user/my-rust/world_hello)
    Finished dev [unoptimized + debuginfo] target(s) in 0.29s
     Running `target/debug/world_hello`
hello, world
1
2
3
4
5

上述代码,cargo run 首先对项目进行编译,然后再运行,因此它实际上等同于运行了两个指令,如同我们下面将做的

手动编译和运行项目

编译:

➜  world_hello git:(master) ✗ cargo build
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
1
2

运行:

➜  world_hello git:(master) ✗ ./target/release/world_hello
Hello, world!
1
2

默认情况下使用 debug 模式编译,特点是:代码的编译速度快,但是运行时稍慢。因为:在 debug 模式下,Rust 编译器不会做任何的优化,只为了尽快的编译完成,让你的开发流程更加顺畅。

使用release模式:

  • cargo run --release
  • cargo build --release
➜  world_hello git:(master) ✗ cargo run --release
   Compiling world_hello v0.1.0 (/Users/user/my-rust/world_hello)
    Finished release [optimized] target(s) in 0.33s
     Running `target/release/world_hello`
hello, world
1
2
3
4
5

cargo check 项目大了之后,难免编译速度降低,因此使用cargo check ,它的作用很简单:快速的检查一下代码能否编译通过. 因此该命令速度会非常快,能节省大量的编译时间.

➜  world_hello git:(master) ✗ cargo check
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
1
2

# cargo.toml 和 cargo.lock

cargo.toml 和 cargo.lock 是 cargo 的核心文件,它的所有活动均基于此二者。

类比 JavaScript 中的 package.jsonpackage-lock.json

package 配置段落 package 中记录了项目的描述信息,典型的如下:

[package]
name = "world_hello"
version = "0.1.0"
edition = "2021"
1
2
3
4
  • name:项目名称
  • version: 当前项目版本
  • edition:Rust 的大版本(2-3 年发布一次大版本)

定义项目依赖 使用 cargo 工具的最大优势就在于,能够对该项目的各种依赖项进行方便、统一和灵活的管理。在 cargo.toml 中,主要通过各种依赖段落来描述该项目的各种依赖项:

  • 基于 rust 官方仓库 crates.io (opens new window),通过版本说明来描述
  • 基于项目源代码的 git 仓库地址,通过 URL 来描述
  • 基于本地项目的绝对路径或者相对路径,通过类 Unix 模式的路径来描述

这三种形式具体写法如下:

[dependencies]
rand = "0.3"
hammer = { version = "0.5.0"}
color = { git = "https://github.com/bjz/color-rs" }
geometry = { path = "crates/geometry" }
1
2
3
4
5
Last Updated: 2/21/2022, 11:35:56 AM