0x01 Getting Started*
- 安装 Rust
- Hello, world!
- 包管理器和构建工具:cargo
Installation*
通过 rustup 下载 Rust,安装最新稳定版 Rust。
$ curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
通过 rustup 安装 Rust 之后,使用 rustup update 更新,使用 rustup self uninstall 卸载。
Hello, World!*
按照惯例,先来个 Hello, world!
fn main() {
println!("Hello, world!");
}
编译运行:
$ rustc main.rs
$ ./main
Hello, world!
和 C 一样,都是以 main 函数为程序入口。
可以使用 rustfmt 来格式化代码。
println! 是一个 Rust 宏,有 ! 就表明是个宏。
和 C 类似,Rust 是预编译静态类型语言。
Hello, Cargo!*
Cargo 是 Rust 的构建系统和包管理器,可以构建代码、下载并编译依赖库。
使用 Cargo 创建项目*
$ cargo new hello_cargo
$ tree hello_cargo
hello_cargo
├── Cargo.toml
└── src
└── main.rs
1 directory, 2 files
Cargo 会创建一个项目目录,同时还会初始化一个 git 仓库,以及一个 .gitignore 文件。
Cargo.toml (TOML, Tom's Obvious, Minimal Lanuage)是 Cargo 项目的配置文件:
[package]
name = "hello_cargo"
version = "0.1.0"
authors = ["root"]
edition = "2018"
[dependencies]
[package] 是一个段标题,表明下面的语句用来配置一个包。
[dependencies] 是项目依赖段的开始。Rust 代码包被称为 crates,如果需要依赖其他的 crates 就添加到这个段中,第二章就会用到。
src/main.rs 中生成了一个 Hello, world! 程序。
构建并允许 Cargo 项目*
使用 cargo build 构建项目。
$ cargo build
Compiling hello_cargo v0.1.0 (/root/rust/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.73s
Cargo 会编译生成一个可执行文件放在 target/debug 目录下。
首次构建还会在项目根目录创建一个 Cargo.lock 文件,用于记录项目依赖的实际版本。
还可以使用 cargo run 同时编译并运行。
如果 Cargo 发现源文件未改动就不会编译。
使用 cargo check 快速检查代码确保可以编译而不生成可执行文件,这样快很多。
使用 cargo build --release 来优化准备发布的项目,会在 target/release 目录下生成文件。
对于拥有多个 crate 的复杂项目,Cargo 比 rustc 更方便。