入门Rust¶
Rust¶
无 GC 且无需手动内存管理、性能高、工程性强、语言级安全性
安装Rust¶
参考网址:https://course.rs/first-try/installation.html 一定要按照安装顺序,不然后续跑程序才报错,查找原因很痛苦
确认安装成功¶
Bash
$ rustc -V
Bash
$ cargo -V
卸载¶
Bash
$ rustup self uninstall
Rust程序¶
- 以rs结尾的文件
- 定义函数: fn main(){}
- 没有参数,没有返回
- main 函数很特别:它是每个 Rust 可执行程序最先运行的代码
- 打印文本: println!("Hello, world!");.
- Rust 的缩进是4个空格而不是 tab
- println! 是一个 Rust macro (宏),如果是函数的话,就没有 ! “Hello World”是字符串,它是 println! 的参数
- 这行代码以;结尾
Cargo¶
- Cargo 是 Rust 的构建系统和包管理工具构建代码、下载依赖的库、构建这些库...
- 安装 Rust 的时候会安装 Cargo-
- cargo --version
创建项目¶
Bash
$ cargo new world_hello
Created binary (application) `world_hello` package

Rust
fn main() {
println!("Hello, world!");
}
运行项目¶
有两种方式可以运行项目: cargo run
Bash
$ cargo run
Compiling world_hello v0.1.0 (D:\Workplace\Rust\study\world_hello)
Finished dev [unoptimized + debuginfo] target(s) in 3.00s
Running `target\debug\world_hello.exe`
Hello, world!
手动编译和运行项目 编译
Bash
运行
$ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.00s
Bash
debug 模式下,代码的编译速度会非常快,可运行速度就慢了. 原因是,在 debug 模式下,Rust 编译器不会做任何的优化,只为了尽快的编译完成,让你的开发流程更加顺畅。
$ target/debug/world_hello
Hello, world!
高性能运行
Bash
$ cargo run --release
Finished release [optimized] target(s) in 0.23s
Running `target\release\world_hello.exe`
Hello, world!
$ cargo build --release
Finished release [optimized] target(s) in 0.00s
$ target/release/world_hello
Hello, world!
快速检测编译是否通过¶
- cargo check,检查代码,确保能通过编译,但是不产生任何可执行文件
- cargo check 要比 cargo build 快得多编写代码的时候可以连续反复的使用 cargo check 检查代码,提高效率
Bash
$ cargo check Finished dev [unoptimized + debuginfo] target(s) in 0.00s
为发布构建¶
Rust
cargo build --release
- 编译时会进行优化
- 代码会运行的更快,但是编译时间更长 -会在 target/release 而不是 target/debug 生成可执行文件
- 两种配置:
- 一个开发
- 一个正式发布
Cargo.toml 和 Cargo.lock¶
Cargo.toml 和 Cargo.lock 是 cargo 的核心文件,它的所有活动均基于此二者。
Text Only
Cargo.toml 是 cargo 特有的项目数据描述文件。它存储了项目的所有元配置信息,如果 Rust 开发者希望 Rust 项目能够按照期望的方式进行构建、测试和运行,那么,必须按照合理的方式构建 Cargo.toml。
Cargo.lock 文件是 cargo 工具根据同一项目的 toml 文件生成的项目依赖详细清单,因此我们一般不用修改它,只需要对着 Cargo.toml 文件撸就行了。
包和依赖¶
在Cargo.toml中配置包和依赖
Bash
[package]
name = "variable"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.4"