Crates.io | rust_beginner |
lib.rs | rust_beginner |
version | 0.1.0 |
created_at | 2025-09-25 04:35:06.036277+00 |
updated_at | 2025-09-25 04:35:06.036277+00 |
description | A project whose codes contain i learn rust from https://kaisery.github.io/trpl-zh-cn/ch14-02-publishing-to-crates-io.html. |
homepage | |
repository | |
max_upload_size | |
id | 1854191 |
size | 43,665 |
https://kaisery.github.io/trpl-zh-cn/ch08-00-common-collections.html https://course.rs/advance/into-types/converse.html
Ownership is a set of rules that govern how a Rust program manages memory. All programs have to manage the way they use a computer’s memory while running. Some languages have garbage collection that regularly looks for no-longer-used memory as the program runs; in other languages, the programmer must explicitly allocate and free the memory. Rust uses a third approach: memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile. None of the features of ownership will slow down your program while it’s running.
Because ownership is a new concept for many programmers, it does take some time to get used to. The good news is that the more experienced you become with Rust and the rules of the ownership system, the easier you’ll find it to naturally develop code that is safe and efficient. Keep at it!
When you understand ownership, you’ll have a solid foundation for understanding the features that make Rust uniqu
// 在同一时间 你可以拥有一个可变引用或者多个不可变引用
// 引用必须是有效的
因为 Cargo 遵循的一个约定:src/main.rs 就是一个与包同名的二进制 crate 的 crate 根。同样的,Cargo 知道如果包目录中包含 src/lib.rs,则包带有与其同名的库 crate,且 src/lib.rs 是 crate 根。crate 根文件将由 Cargo 传递给 rustc 来实际构建库或者二进制项目。
模块是靠文件名来搜索的 默认模块文件名为lib.rs 如果里面声明了拥有子模块 就会去src下找 如果子模块下还有其他的模块,就会去src/子模块文件名/下面找
需要注意的一点的是, 应该认为当mod被拆分到文件这一级别时,就已经自然拥有mod hosting这类东西. 如果想要修改作用域之类的, 你应该在父模块完成这个操作.
因为 ? 运算符被定义为从函数中提早返回一个值,这与示例 9-6 中的 match 表达式有着完全相同的工作方式。示例 9-6 中 match 作用于一个 Result 值,提早返回的分支返回了一个 Err(e) 值。函数的返回值必须是 Result 才能与这个 return 相兼容。
第一条规则是编译器为每一个引用参数都分配一个生命周期参数。换句话说就是,函数有一个引用参数的就有一个生命周期参数:fn foo<'a>(x: &'a i32),有两个引用参数的函数就有两个不同的生命周期参数,fn foo<'a, 'b>(x: &'a i32, y: &'b i32),依此类推。
第二条规则是如果只有一个输入生命周期参数,那么将它赋予给所有输出生命周期参数:fn foo<'a>(x: &'a i32) -> &'a i32。
第三条规则是如果方法有多个输入生命周期参数并且其中一个参数是 &self 或 &mut self,说明这是个方法,那么所有输出生命周期参数被赋予 self 的生命周期。第三条规则使得方法更容易读写,因为只需更少的符号。
$ cargo test -- --test-threads=1 $ cargo test -- --show-output cargo test -- --ignored
单元测试和项目代码在同一个文件夹里面
在函数的参数传递的时候 允许 &str = &&str 自动解引用 &str = &String 实现了相关的trait因此可以 不允许 &String = String
Rust 的设计哲学之一是:“你必须明确表达你的意图”。
如果你想引用某个值,你必须显式写 &。
这避免了“隐式借用”导致的生命周期和悬垂引用问题。
let example_closure = |x| x;
let s = example_closure(String::from("hello"));
let n = example_closure(5);
FnOnce 适用于只能被调用一次的闭包。所有闭包至少都实现了这个 trait,因为所有闭包都能被调用。一个会将捕获的值从闭包体中移出的闭包只会实现 FnOnce trait,而不会实现其他 Fn 相关的 trait,因为它只能被调用一次。
FnMut 适用于不会将捕获的值移出闭包体,但可能会修改捕获值的闭包。这类闭包可以被调用多次。
Fn 适用于既不将捕获的值移出闭包体,也不修改捕获值的闭包,同时也包括不从环境中捕获任何值的闭包。这类闭包可以被多次调用而不会改变其环境,这在会多次并发调用闭包的场景中十分重要。