1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-01-05 16:10:31 +02:00

Suggesting to add Default to important traits. (#243)

* Suggesting to add `Default` to important traits.

This is a great trait to know about, it is used very often.

* Change `Implemented` to tuple struct.

It saves vertical space.
This commit is contained in:
Igor Petruk 2023-02-06 19:17:21 +00:00 committed by GitHub
parent fd82a95e85
commit ab831de1da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 49 additions and 0 deletions

View File

@ -134,6 +134,7 @@
- [Read and Write](traits/read-write.md)
- [Add, Mul, ...](traits/operators.md)
- [Drop](traits/drop.md)
- [Default](traits/default.md)
- [Generics](generics.md)
- [Generic Data Types](generics/data-types.md)
- [Generic Methods](generics/methods.md)

47
src/traits/default.md Normal file
View File

@ -0,0 +1,47 @@
# The `Default` Trait
`Default` trait provides a default implementation of a trait.
```rust,editable
#[derive(Debug, Default)]
struct Derived {
x: u32,
y: String,
z: Implemented,
}
#[derive(Debug)]
struct Implemented(String);
impl Default for Implemented {
fn default() -> Self {
Self("John Smith".into())
}
}
fn main() {
let default_struct: Derived = Default::default();
println!("{default_struct:#?}");
let almost_default_struct = Derived {
y: "Y is set!".into(),
..Default::default()
};
println!("{almost_default_struct:#?}");
let nothing: Option<Derived> = None;
println!("{:#?}", nothing.unwrap_or_default());
}
```
<details>
* It can be implemented directly or it can be derived via `#[derive(Default)]`.
* Derived implementation will produce an instance where all fields are set to their default values.
* This means all types in the struct must implement `Default` too.
* Standard Rust types often implement `Default` with reasonable values (e.g. `0`, `""`, etc).
* The partial struct copy works nicely with default.
* Rust standard library is aware that types can implement `Default` and provides convenience methods that use it.
</details>

View File

@ -7,3 +7,4 @@ We will now look at some of the most common traits of the Rust standard library:
* `Read` and `Write` used for IO,
* `Add`, `Mul`, ... used for operator overloading, and
* `Drop` used for defining destructors.
* `Default` used to construct a default instance of a type.