Rust入门秘笈 (Rust)(Z-Library)
rust
No Description
205
Views
0
Downloads
0.00
Total Donations
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
Rust简介 Rust程式设计语言旨在提供更好的记忆体安全性,但它仍处于维护过程中。 Rust是什么? Rust是由Mozilla员工「Graydon Hoare」于2006年开发的系统程式设计语言。他将这种语言描述 为支援功能和命令正规化的「安全,并行和实用的语言」。 Rust的语法类似于C++语言。 Rust是免费的开源软体,即任何人都可以自由使用该软体,并且公开共用原始码,以便人们也可以 改进软体的设计。 Rust在2016年,2017年和2018年的堆叠溢位开发者调查中被宣布为「最受欢迎的程式设计语言」 之一。 没有像 这意味着,记忆体由Rust内部管理。 calloc``malloc Rust的使用者有哪些? 出于多种原因,Rust语言对许多人来说是理想的。 下面来看看吧: 开发团队 低阶程式设计程式码包含需要测试人员进行大量测试的错误。但是,在Rust的情况下, 如果程式包含错误,编译器拒绝编译程式码。通过与编译器并行工作,开发人员可以专注于程式的 逻辑而不是专注于错误。 学生 Rust团队正在努力使普通人更容易理解系统概念,特别是那些不熟悉程式设计的人。 公司 这些任务包括命令列工具,Web服务,DevOps工具,嵌入式装置,音讯和视讯分析和转码, 加密货币,生物资讯学,搜寻引擎,物联网应用程式,机器学习,甚至Firefox Web浏览器的重要 部分。 开源开发人员 因此,他们可以使用原始码来改进Rust的设计。
Page
2
Rust的特点 Rust是一种系统程式设计语言,Rust提供以下功能: 零成本抽象 错误讯息 移动语意 没有资料竞争的执行绪 模式匹配 保证记忆体安全 高效的C系结 安全的记忆体空间分配 最少的时间 1.零成本抽象 在Rust中,可以新增抽象而不会影响程式码的执行时效能。它提高了程式码品质和程式码的可读性,而 无需任何执行时效能成本。 2.错误讯息 在C++程式设计中,与GCC相比,错误讯息有了很好的改进。在清晰的情况下,Rust更进一步提高。错 误讯息显示为(格式,颜色),并在程式中建议拼写错误。 3.型别推断 Rust提供了型别推断的功能,这意味着它可以自动确定表示式的型别。 4.移动语意 Rust提供此功能,允许在源物件是临时物件时,通过移动操作替换复制操作。 5.没有资料争用的执行绪 资料争用是两个或多个执行绪存取同一记忆体位置的条件。由于所有权系统,Rust提供了没有资料争用 的执行绪功能。所有权系统仅将不同物件的所有者传输到不同的执行绪,并且两个执行绪永远不能拥有 具有写存取许可权的相同变数。 6.模式匹配 Rust提供了模式匹配的功能。在模式匹配中,Rust中的模式与'match'表示式一起使用,以更好地控制程 式的控制流。以下是一些模式的组合: 字面量 阵列,列举,结构或元组 变数 万用字元 预留位置 7.保证记忆体安全 Rust通过使用所有权的概念保证了记忆体安全。所有权是C语言的记忆体控制和java的垃圾收集之间的中 间地带。在Rust程式中,记忆体空间由变数拥有,并由其他变数暂时借用。这允许Rust在编译时提供记 忆体安全性,而不依赖于垃圾收集器。
Page
3
8.高效的C系结 Rust提供了「高效C系结」的功能,这意味着Rust语言能够在与自身对话时与C语言进行互操作。Rust提 供了一个「外部功能介面」来与C API进行通讯,并利用其所有权系统同时保证记忆体安全。 9.安全的记忆体空间分配 在Rust中,记忆体管理是手动的,即程式员可以明确控制分配和释放记忆体的位置和时间。在C语言 中,使用 此运算子将智慧指标返回为 智慧指标是一种特殊的值,用于控制何时释放物件。智慧指标是 「智慧的」,因为它们不仅跟踪物件的位置,而且还知道如何清理它。 malloc``~``int
Page
4
Rust开发环境安装 在学习Rust之前。首先,需要安装Rust,通过 rustup Windows上Rust安装 在Windows上,开启连结 按照所有说明操作后,将安装Rust并显示萤幕: rustup-init.exe 接着回车 - 然后开始下载并安装Rust 环境。 安装后,Rust的PATH变数会自动新增到系统PATH中。开启命令提示字元然后执行以下命令:
Page
5
执行此命令后,应该看到版本号,提交的杂凑值和提交日期。如果看到类似的结果,则表示Rust已成功 安装。 结果如下所示 - 注意:使用C++工具安装visual studio是执行rust程式的必要条件。 Linux或macOS中的Rust安装 如果使用的是Linux或macOS,请开启终端然后使用以下命令: 上面的命令下载指令码并开始安装Rust工具,它将安装最新版本的Rust。如果安装成功完成,则会显示 以下讯息: 下次登入后,此安装会自动将Rust新增到系统路径中。如果要立即执行Rust而不重新启动终端,请执行 以下命令到 shell 安装后,需要一个连结器。当尝试执行Rust程式时,将收到连结器无法执行的错误。这意味着系统中未 安装连结器。C编译器总是提出正确的编译器。安装C编译器。另外,一些Rust包依赖于C程式码,需要 一个C编译器。 更新和解除安装 更新:执行以下命令以更新到最新版本: 解除安装: $ rustc --version C:\Users\hema>rustc --version rustc 1.30.0 (da5f414c2 2018-10-24) $ curl https://sh.rustup.rs -sSf | sh Rust is installed now. Great! $ source $HOME/.cargo/env $ rustup update $ rustup self uninstall
Page
6
Rust第一个程式 在本文中,使用Rust语言编写简单的程式,以了解如何编写,储存和编译Rust程式。现在,开启记事本 档案并编写以下程式码: 将上面内容储存到一个档案: rustc hello.rs main():函式用大括号 函式不包含任何引数,也不返回任何值。 main()``main()``{}``main() println!:这是一个Rust巨集。如果它呼叫该函式,则它不包含符号: '!' "Hello World":它是作为引数传递给 println! 建立,编译和执行程式的过程 1. 开启记事本档案并将程式码写入记事本档案中。 2. 使用 .rs 3. 开启命令提示字元 4. 设定目录的路径,假设专案位于 /home/hema/worsp/rust 5. 使用 rustc 6. 最后,使用命令 ./filename 注:如果有遇到「error: could not exec the linker link.exe fn main(){ println!("Hello, world!"); } Hello, world! hema@yiibai:~/worsp/rust$ rustc hello.rs && ./hello Hello World!
Page
7
Rust if语句 表示 if if块 if-else块 if else-if阶梯块 巢状if语句 if语句 if语句块的语法 - 在上面的语法中,如果条件为真,则执行块语句,否则跳过 if if语句的流程图 - 范例: if 执行上面范例程式码,得到以下结果: if`语句确定条件是否为真。如果条件为`true``if``if if condition { //block statements; } fn main(){ let a=1; if a==1 { println!("a is equal to 1"); } }
Page
8
在这个例子中,因此, a``1``if``println! if-else语句 如果条件为真,则执行 如果条件为假,则跳过 if``else``if``else if-else语句的语法 if-else的流程图 下面来看看一个 if-else 执行上面范例程式码,得到以下结果 - a is equal to 1 if condition { //block statements }else{ //block statements } fn main() { let a=3; let b=4; if a>b { println!("a is greater than b"); } else { println!("a is smaller than b"); } }
Page
9
在该范例中,变数 因此,执行 a``3``a``b``else else-if语句 如果要检查多个条件,则可使用 else-if else-if语句的语法 - 在上面的语法中,Rust为第一个真实条件执行块,当匹配到第一个真条件时,它就不会执行其余的块。 else if语句块的流程图 - 下面来看一个 else-if a is smaller than b if condition 1 { //block statements }else if condition 2 { //block statements } . . else{ //block statements } fn main(){ let num= -5; if num>0 { println!("number is greater than 0"); } else if num<0
Page
10
执行上面范例程式码,得到以下结果 - 在此范例中,变数 因此, num``-5``num``0``else if 巢状if-else语句 当 巢状 if-else``if``else``if-else if-else 下面来看一个巢状 if-else { println!("number is less than 0 "); } else { println!("number is not equal to 0"); } } number is less than 0 if condition 1 { // 巢狀if/else塊 if condition 2 { //block statements }else { //block statements } }else{ //block statements } fn main(){ let a=5; let b=6; if a!=b { if a>b { println!("a is greater than b"); }else{ println!("a is less than b"); } } else { println!("a is equal to b"); } }
Page
11
执行上面范例程式码,得到以下结果 - 在此范例中,因此,控制进入 因此,执行 a``b``if``a``b``else``if a is less than b
Page
12
Rust if in a let语句 在 let``if``if``let if in a let语法 在上面的语法中,如果条件为真,则将 if``false``else 范例1 下面来看一个简单的例子。 执行上面范例程式码,得到以下结果 - Let variable_name= if condition{ //code blocks }else{ //code block } fn main(){ let a=if true { 1 } else { 2 }; println!("value of a is: {}", a); } value of a is: 1
Page
13
在此范例中,条件为真。因此,现在, a``if``a``1 下面再来看一个另一个简单的例子。 执行上面范例程式码,得到以下结果 - 在此范例中,因此,该程式丢掷错误,因为两个块都包含不同型别的值。 if``else fn main(){ let a=if false { 9 } else { "yiibai" }; println!("value of a is: {}", a); } Some errors occurred:E0308
Page
14
Rust loop回圈 如果想要多次执行语句块,那么回圈概念就属于这个角色。回圈执行回圈体记忆体在的程式码直到结 束,并从启动开始立即重新开始。 Rust有三种回圈: loop回圈 for回圈 while回圈 loop回圈 loop不是条件回圈。它是一个关键字,告诉Rust一次又一次地执行程式码块,直到除非明确地手动停 止回圈。 loop回圈 在上面的语法中,块语句被无限次执行。 回圈流程图: 下面来看看一个无限回圈的简单例子 - loop{ //block statements } fn main(){ loop { println!("Hello Yiibai"); } }
Page
15
执行上面范例程式码,得到以下结果 - 在这个例子中,「Hello Yiibai」字串一遍又一遍地列印,直到除非手动停止回圈。通常,「ctrl + c」命 令用于从回圈终止。 回圈终止 下面来看一个简单的例子 - 执行上面范例程式码,得到以下结果 - 在上面的例子中, i Hello Yiibai Hello Yiibai Hello Yiibai Hello Yiibai . . . infinite times break`关键字用于从回圈终止。如果未使用`break fn main() let mut i=1; loop { println!("Hello Yiibai"); if i==7 { break; } i+=1; } } Hello Yiibai Hello Yiibai Hello Yiibai Hello Yiibai Hello Yiibai Hello Yiibai Hello Yiibai
Page
16
Rust for回圈 for回圈的语法 - 在上面的语法中,表示式可以转换为叠代器,叠代器遍历资料结构的元素。在每次叠代中,都从叠代器 中获取值。当没有剩余值被提取时,回圈结束。 下面来看一个简单的例子。 执行上面范例程式码,得到以下结果 - 在上面的范例中,上限是不包含的,因此回圈将列印 1..11``1``10 下面再来看一个简单的例子。 执行上面范例程式码,得到以下结果 - for`回圈是条件回圈,即回圈执行特定次数。Rust语言中 执行`for``for for var in expression { //block statements } fn main() { for i in 1..11 { print!("{} ",i); } } 1 2 3 4 5 6 7 8 9 10 fn main() { let mut result; for i in 1..11 { result=2*i; println!("2*{}={}",i,result); } }
Page
17
在上面的例子中, for``2 下面来看另一个简单的例子。 执行上面范例程式码,得到以下结果 - 在上面的例子中,当它到达阵列的最后一个元素,那么回圈就结束了。 iter()``fruits while回圈和for回圈的区别:因此,可以说 while``for``for 2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20 fn main(){ let fruits=["mango","apple","banana","litchi","watermelon"]; for a in fruits.iter() { print!("{} ",a); } } mango apple banana litchi watermelon
Page
18
Rust while回圈 while-loop是一个条件回圈。当程式需要评估条件时,则使用条件回圈。当条件为真时,它执行回 圈,否则它终止回圈。 while回圈的语法 在上面的语法中,如果条件为真,则执行块语句,否则终止回圈。Rust提供了这个内建构造,可以与 while``loop``if``else``break while回圈流程图 下面来看一个简单的例子 - 执行上面范例程式码,得到以下输出结果 - while condition //block statements; fn main() { let mut i=1; while i<=10 { print!("{}", i); print!(" "); i=i+1; } } 1 2 3 4 5 6 7 8 9 10
Page
19
在上面的例子中,回圈执行直到 i``i``while``i``10``10 下面来看一个简单的例子 输出结果 - 在上面的范例中,使用 while while回圈的缺点: 如果索引长度不正确,回圈可能会导致问题。 当编译器新增执行时程式码以通过此回圈对每次叠代执行条件检查时,它也很慢。 fn main() { let array=[10,20,30,40,50,60]; let mut i=0; while i<6 { print!("{}",array[i]); print!(" "); i=i+1; } } 10 20 30 40 50 60
Page
20
Rust所有权 所有权是Rust程式设计语言提供的独特功能,可在不使用垃圾收集器或指标的情况下提供记忆体安全保 障。 什么是所有权? 当程式码块拥有资源时,它被称为所有权。程式码块建立一个包含资源的物件。当控制元件到达块的末 尾时,物件将被销毁,资源将被释放。 所有权的重点: 「所有者」可以根据可变性改变变数的拥有值。 所有权可以转移到另一个变数。 所有权只是在Rust中移动语意。 所有权模型也保证了并行的安全性。 所有权规则 在Rust中,每个值都有一个与之关联的变数,并称为其所有者。 一次只能有一个所有者。 当所有者超出范围时,与其关联的值将被销毁。 所有权的例子 多个变数可以在Rust中相互互动。下面来看一个例子: 将 x``y 在上面的例子中,然后,在这种情况下,不会建立 因此,如果尝试重用变数 可通过下面的例子来理解这 一点。 x``10``x``y``x``x``y``x``y``x``x 编译上面程式码,范例的输出如下: let x=10; let y=x; fn main() { let x=10; let y=x; println!("value of x :{}",x); }
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A practical, example-driven introduction to Rust for beginners who want to learn the language's core concepts—ownership, borrowing, structs, enums, and error handling—without getting lost in theory. Ideal for programmers coming from C/C++ or other systems languages who want a hands-on, code-first entry point.
【Book Arc】
- **Opening (~0%–6%)**: Introduces Rust's origins, philosophy (memory safety without garbage collection), and installation via `rustup`. Walks through the first "Hello, world!" program, compilation with `rustc`, and basic control flow (`if`, `if-else`, nested conditions), establishing the syntax and toolchain fundamentals.
- **Early (~6%–18%)**: Covers loops (`loop`, `for`, `while`) and then dives into Rust's signature feature—ownership. Explains the rules (single owner, move semantics, scope-based destruction), the `Copy` trait for stack-only types, and introduces references and borrowing, including the key restriction of one mutable reference at a time.
- **Early (~18%–29%)**: Continues with slices (string slices, range syntax) and moves into user-defined types: structs (definition, instantiation, field access, update syntax) and methods via `impl` blocks, emphasizing the `self` parameter and method-call syntax.
- **Middle (~29%–41%)**: Introduces enums and the `match` operator, including `Option<T>` and the `if let` shorthand. Then shifts to modules: file organization (`mod` declarations, `src/lib.rs`), visibility rules with `pub`, and the `use` and `super` keywords for path management.
- **Middle (~41%–59%)**: Focuses on collections—vectors (creation, indexing with `[]` vs. `get()`, mutation, updating, deletion, storing mixed types via enums) and strings (creation, updating with `push_str` and `format!`, and why strings can't be indexed due to UTF-8 encoding).
- **Late (~59%–end)**: Covers error handling: the distinction between recoverable (`Result<T, E>`) and unrecoverable (`panic!`) errors, plus macros like `assert!` and `unreachable!`. Discusses unwinding vs. aborting on panic and how to configure `panic = 'abort'`.
【Key Takeaways】
- **Ownership is Rust's core safety mechanism** (Early): Every value has a single owner; when the owner goes out of scope, the value is dropped. This eliminates garbage collection and manual memory management, preventing double-free and use-after-free bugs.
- **Move semantics and the `Copy` trait** (Early): Assignment transfers ownership for heap types (like `String`), making the old variable unusable. Stack-only types (integers, booleans, floats, chars) implement `Copy`, so they remain valid after assignment—knowing which types are `Copy` prevents compile errors.
- **Borrowing allows multiple references without violating single ownership** (Early): References (`&T`) let functions access data without taking ownership. The key rule: you can have either many immutable references or one mutable reference (`&mut T`) in a scope, never both—this prevents data races at compile time.
- **Slices provide safe, zero-copy access to collections** (Early): A slice (`&str[0..10]`) references a contiguous portion of data without owning it. Range syntax (`..`, `..=`) is inclusive/exclusive as specified, and string literals are themselves slices stored in the binary.
- **Structs and enums are the building blocks of custom types** (Early–Middle): Structs group related fields with named types; enums define a type with a fixed set of variants. The `match` operator exhaustively handles all variants, and `if let` offers a concise alternative for single-pattern matches.
- **Modules organize code and control visibility** (Middle): Files map to modules (`mod` declarations, `src/lib.rs`), with `pub` controlling external access. The `use` keyword shortens paths, and `super` accesses parent modules—essential for structuring larger projects.
- **Vectors and strings have distinct access patterns** (Middle): Vectors support indexing with `[]` (panics on out-of-bounds) or `get()` (returns `Option<&T>` for safe handling). Strings are UTF-8 encoded and cannot be indexed by byte position; use `push_str`, `format!`, or slicing with care.
- **Error handling is explicit, not exception-based** (Late): Recoverable errors use `Result<T, E>` with `Ok`/`Err` variants; unrecoverable errors trigger `panic!`. Macros like `assert!` and `unreachable!` enforce invariants, and you can choose between stack unwinding and aborting via `panic = 'abort'`.
【Reading Tips】
- **Skim the installation and toolchain sections** (Opening): If you already have Rust installed via `rustup`, jump straight to the "Hello, world!" example and the control-flow sections—these are quick wins for syntax familiarity.
- **Deep-read the ownership and borrowing chapters** (Early): These are the hardest and most important concepts. Work through the code examples line by line, especially the move/copy distinction and the mutable-reference restriction. Recreate the examples yourself to internalize the rules.
- **Use the struct, enum, and module sections as reference material** (Early–Middle): The patterns here (struct update syntax, `impl` methods, `match` with enums, module file organization) are foundational for real Rust projects. Skim the theory, but type out the examples to see how they compile and run.
- **Pay attention to the vector and string gotchas** (Middle): The `[]` vs. `get()` difference and the UTF-8 indexing error are common beginner pitfalls. Note the error messages shown—they're typical of what you'll encounter and worth recognizing.
- **Treat the error-handling section as a mindset shift** (Late): Rust's explicit error handling differs from exceptions in other languages. Focus on the `Result` type and `panic!` behavior, and note the `unreachable!` macro as a debugging aid—this will prepare you for writing robust production code.
【Coverage Limits】
This guide covers the book's progression from syntax basics through ownership, types, modules, collections, and error handling. The excerpts do not cover advanced topics like traits, generics (beyond `Option<T>`), lifetimes, concurrency, or C interop in depth—those are mentioned but not elaborated in the sampled material.
Passage locations
Page 8
f a>b println!("a is greater than b"); else println!("a is smaller than b"); } 执行上面范例程式码,得到以下结果 - println!("number is less than 0 "); el...
View in text
Excerpt 2
多次参照,但仍然遵守「单一所有者」。 参照就像C中的指标一样。 参照是一个物件。参照有两种型别,即可变参照和不可变参照。在复制不可变参照时移动可变参 照。 下面通过一个例子来理解这一点。 fn main() let str=String::from("Yiibai"); let len=calculate...
View in text
Excerpt 3
language(Computerlanguage::Csharp); } 执行上面范例程式码,得到以下结果 - C language C++ language Java language C# language 在上面的范例中,匹配运算子将语言的值与匹配运算子块中给出的表示式匹配。 Computerlang...
View in text
Excerpt 4
xample { use super::x; pub fn foo() { println!("{}",x()); fn main() a::example::foo(); } 输出结果如下 - 2 在上面的范例中,模组范例使用了参照其父...
View in text
Support Author
0.00
Total Amount (¥)
0
Donation Count
Please enter an amount
Minimum ¥1
You will be redirected to Alipay to complete payment, then return here.
Order created — please complete Alipay payment
{{#payUrl}} Pay with Alipay {{/payUrl}} {{^payUrl}}{{message}}
{{/payUrl}}
Donation failed:{{message}}
Log in to link the donation to your account (anonymous payment also works)
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later