Skip to content

Commit e29dbe8

Browse files
author
Brandon Pollack
committed
Added construction chapter
1 parent bee9cda commit e29dbe8

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
- [Enum Sizes](enums/sizes.md)
7878
- [Methods](methods.md)
7979
- [Method Receiver](methods/receiver.md)
80+
- [Construction](structs/struct-construction.md)
8081
- [Example](methods/example.md)
8182
- [Pattern Matching](pattern-matching.md)
8283
- [Destructuring Enums](pattern-matching/destructuring-enums.md)

src/structs/struct-construction.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Construction
2+
3+
Unlike in C++ or Java, there is no "constructor" in rust for structs, all
4+
construction is done using struct construction syntax.
5+
6+
It is convention, however, to either implement the Default trait, or create a
7+
method called "new" that has no receiver (ie a "static" function).
8+
9+
```rust,editable
10+
struct Person {
11+
name: String,
12+
age: u8,
13+
}
14+
15+
impl Person {
16+
pub fn new(name: String, age: u8) -> Person {
17+
Person {
18+
name,
19+
age
20+
}
21+
}
22+
23+
pub fn new_birth(name: String) -> Person {
24+
Self::new(name, 0)
25+
}
26+
}
27+
28+
fn main() {
29+
let peter = Person::new(String::from("Peter"), 23);
30+
31+
println!("{} is {} years old", peter.name, peter.age);
32+
}
33+
```
34+
35+
<details>
36+
37+
* Mention the `Self` static scope accessor, it allows you to access any method of a struct.
38+
39+
* In fact, dot method call syntax is just syntactic sugar, you can even access methods with &self receiver parameters by explicitly passing structs in to the first parameter, eg `Person::display(&peter)` if it had such a method `display(&self)`.
40+
41+
* Mention it is likely better to take string references and clone them in the construction methods, but we wanted to keep the example simple and consistent with others.
42+
43+
</details>

0 commit comments

Comments
 (0)