Skip to content

Commit c6616d1

Browse files
committed
Merge remote-tracking branch 'origin/main' into github-pages
2 parents 8206197 + 6c28f46 commit c6616d1

File tree

2 files changed

+143
-124
lines changed

2 files changed

+143
-124
lines changed

content/en/docs/b2.structs.md

Lines changed: 58 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ slug: structs
44
---
55

66
- Used to **encapsulate related properties into one unified data type**.
7-
- By convention, the name should follow **[PascalCase](https://en.wikipedia.org/wiki/Camel_case)**.
7+
- By convention, the name should follow [`PascalCase`](https://en.wikipedia.org/wiki/Camel_case).
88
- 3 variants,
99
- C-like structs: One or more `,` separated `name: value pairs` enclosed in `{}`
1010

@@ -22,15 +22,19 @@ slug: structs
2222
struct Color(u8, u8, u8);
2323
```
2424

25-
- Unit structs: A struct with no members
25+
- Unit structs: A struct with no fields/ members
2626

2727
```rust
2828
struct Black;
2929
```
3030

31-
⭐️ When regarding OOP in Rust, attributes and methods are placed separately on **structs** and **traits**. Structs contain only attributes, traits contain only methods. They are getting connected via **impls**.
32-
33-
> 💯 More complex examples can be found on [impls & traits](/docs/impls-and-traits), [lifetimes](/docs/lifetimes) and [modules](/docs/modules) sections.
31+
> ⭐️ When regarding OOP in Rust, attributes and methods are placed separately on **structs** and **traits**. Structs contain only attributes, traits contain only methods. They are getting connected via **impls**.
32+
>
33+
> 💡 In Rust, the term "instantiation" is used to describe the act of creating a concrete instance of a type (struct or enum).
34+
>
35+
> 💡 In Rust, the term "field" is used to describe a named component in a C-like struct & struct-like enum variant, and the term "element" is used to describe an unnamed component in a tuple struct & tuple-like enum variant. The term "member" is used to describe both.
36+
>
37+
> 💯 More complex examples can be found on [Impls and Traits](/docs/impls-and-traits), [Lifetimes](/docs/lifetimes) and [Modules](/docs/modules) sections.
3438

3539
## C-like Structs
3640

@@ -47,7 +51,7 @@ struct Color {
4751
}
4852
```
4953

50-
### Initialization & Accessing Fields
54+
### Instantiation & Accessing Fields
5155

5256
```rust
5357
struct Color {
@@ -57,21 +61,21 @@ struct Color {
5761
}
5862

5963
fn main() {
60-
// 1. Initialization
64+
// 1. Instantiation
6165
let white = Color {
6266
red: 255,
6367
green: 255,
6468
blue: 255,
6569
};
6670

67-
// 2. Initialization without redundant field names, when using the same variable names
71+
// 2. Instantiation without redundant field names, when using the same variable names
6872
let (red, green, blue) = (0, 0, 0);
6973
let black = Color { red, green, blue };
7074

71-
// 3. Initialization + copy elements from another instance
75+
// 3. Instantiation + copy fields' values from another instance
7276
let red = Color { red: 255, .. black }; // 💡 Copy green and blue from black
7377
let green = Color { green: 255, .. black }; // 💡 Copy red and blue from black
74-
let mut blue = Color { .. black }; // 💡 Copy all elements from black
78+
let mut blue = Color { .. black }; // 💡 Copy all fields' values from black
7579
blue.blue = 255;
7680

7781
println!("RGB({}, {}, {})", white.red, white.green, white.blue); // RGB(255, 255, 255)
@@ -84,23 +88,24 @@ fn main() {
8488
```
8589

8690
```rust
87-
// 4. Initialization with default values
91+
// 4. Instantiation with default values
92+
8893
#[derive(Default)]
8994
struct Person {
9095
name: String,
9196
age: f32,
9297
}
9398

9499
fn main() {
95-
let a = Person::default(); // Initialization with default values
100+
let a = Person::default(); // Instantiation with default values
96101

97102
assert_eq!(a.name, ""); // String default value ""
98103
assert_eq!(a.age, 0.0); // f32 default value 0.0
99104
}
100-
101-
// 💡 #[derive(Default)] attribute automatically generates a default implementation for the Default trait for a struct or enum.
102105
```
103106

107+
💡 In Rust, the `#[derive()]` attribute is used to automatically generate an implementation of certain traits for a custom data structure (struct and enum), instead of you writing them by hand. The [`std::default::Default`](https://doc.rust-lang.org/std/default/trait.Default.html) trait allows us to create a new instance of a type with the `Type::default()` method.
108+
104109
💯 5. We can also use a constructor function inside an `impl` block to initialize a struct.
105110

106111
### Destructuring
@@ -124,42 +129,14 @@ fn main() {
124129
company_name: "Apple".to_string(),
125130
};
126131

127-
let Person {name: a, company_name: b} = steve; // 1. Destructuring elements to a and b
132+
let Person {name: a, company_name: b} = steve; // 1. Destructuring fields' values to a and b
128133
println!("{a} {b}"); // Steve Jobs Apple
129134

130-
let Person {company_name: c, .. } = get_steve(); // 2. Destructuring only selected elements + a struct returned from a function
135+
let Person {company_name: c, .. } = get_steve(); // 2. Destructuring only selected fields' values; directly from the function call
131136
println!("{c}"); // Apple
132137
}
133138

134-
// 💯 let Person {name: ref a, company_name: ref b} = steve; // add ref keyword, to pass an element as a reference
135-
```
136-
137-
### Debug Printing and Pretty Debug Printing
138-
139-
> 💡 `#[derive(Debug)]` attribute is used to automatically generate an implementation of the `Debug trait` for a custom data structure, such as a `struct` or an `enum`.
140-
141-
```rust
142-
#![allow(unused)] // 💡 skip unused warnings in crate/ module level
143-
144-
#[derive(Debug)]
145-
struct Person {
146-
name: String,
147-
company_name: String,
148-
}
149-
150-
fn main() {
151-
let (name, company_name) = ("Steve Jobs".to_string(), "Apple".to_string());
152-
let a = Person { name, company_name };
153-
154-
println!("{a:?}"); // 💡 Debug printing with :? format specifier
155-
// Person { name: "Steve Jobs", company_name: "Apple" }
156-
157-
println!("{a:#?}"); // 💡 Pretty-debug printing with :#? format specifier
158-
// Person {
159-
// name: "Steve Jobs",
160-
// company_name: "Apple",
161-
// }
162-
}
139+
// 💯 let Person {name: ref a, company_name: ref b} = steve; // add ref keyword, to pass a field's value as a reference
163140
```
164141

165142
## Tuple Structs
@@ -176,7 +153,7 @@ struct Color(u8, u8, u8);
176153
struct Department(String);
177154
```
178155

179-
### Initialization & Accessing Elements
156+
### Instantiation & Accessing Elements
180157

181158
```rust
182159
struct Color(u8, u8, u8);
@@ -206,43 +183,20 @@ fn get_department() -> Department {
206183
fn main() {
207184
let white = Color(255, 255, 255);
208185

209-
let Color(red, green, blue) = white; // 💡 let Color(red, blue, .. ) = white; // Destructuring only selected elements
186+
let Color(red, green, blue) = white; // 💡 let Color(red, blue, .. ) = white; // Destructuring only selected field's value
210187
println!("RGB({}, {}, {})", red, green, blue); // RGB(255, 255, 255)
211188

212189
let Department(name) = get_department();
213190
println!("{}", name); // Engineering
214191
}
215192
```
216193

217-
### Debug Printing and Pretty Debug Printing
218-
219-
```rust
220-
#![allow(unused)]
221-
222-
#[derive(Debug)]
223-
struct Department(String);
224-
225-
fn main() {
226-
let a = Department("Engineering".to_string());
227-
228-
println!("{a:?}");
229-
// Department("Engineering")
230-
231-
println!("{a:#?}");
232-
// Department(
233-
// "Engineering",
234-
// )
235-
}
236-
```
237-
238194
## Unit Structs
239195

240-
- It defines a new type, but it resembles an empty tuple, \(\)
196+
- It defines a new type, but it resembles an empty tuple, `()`
241197
- This is rarely useful on its own. But in combination with other features (such as generics), it can become useful.
242198

243-
> [📖](https://doc.rust-lang.org/book/first-edition/structs.html) ex: A library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can create a unit-like struct.
244-
245-
### Definition & Initialization
199+
### Definition & Instantiation
246200

247201
```rust
248202
struct Electron;
@@ -252,15 +206,44 @@ fn main() {
252206
}
253207
```
254208

255-
### Debug Printing and Pretty Debug Printing
209+
> [📖](https://doc.rust-lang.org/book/first-edition/structs.html) ex: A library may ask you to create a structure that implements a certain trait to handle events. If you don’t have any data you need to store in the structure, you can create a unit-like struct.
210+
211+
## Debug Printing and Pretty Debug Printing
212+
213+
In Rust, the `#[derive()]` attribute is used to automatically generate an implementation of certain traits for a custom data structure (struct and enum), instead of you writing them by hand. The [`std::fmt::Debug`](https://doc.rust-lang.org/std/fmt/trait.Debug.html) trait allows us to format a value with `{:?}` or `{:#?}` in `println!` and similar macros.
256214

257215
```rust
216+
#![allow(unused)] // 💡 skip unused warnings, as we don't read fields in the structs
217+
258218
#[derive(Debug)]
259219
struct Electron;
260220

221+
#[derive(Debug)]
222+
struct Department(String);
223+
224+
#[derive(Debug)]
225+
struct Person {
226+
name: String,
227+
company_name: String,
228+
}
229+
261230
fn main() {
262231
let a = Electron;
263-
println!("{a:?}"); // Electron
264-
println!("{a:#?}"); // Electron
232+
println!("{a:?}"); // Electron // 💡{a:#?} prints the same
233+
234+
let b = Department("Engineering".to_string());
235+
println!("{b:?}"); // Department("Engineering")
236+
println!("{b:#?}");
237+
// Department(
238+
// "Engineering",
239+
// )
240+
241+
let c = Person { name: "Steve Jobs".to_string(), company_name: "Apple".to_string() };
242+
println!("{c:?}"); // Person { name: "Steve Jobs", company_name: "Apple" }
243+
println!("{c:#?}");
244+
// Person {
245+
// name: "Steve Jobs",
246+
// company_name: "Apple",
247+
// }
265248
}
266249
```

0 commit comments

Comments
 (0)