diff --git a/src/SUMMARY.md b/src/SUMMARY.md index e42dbf56f1bb..1fff51bcf794 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -77,6 +77,7 @@ - [Enum Sizes](enums/sizes.md) - [Methods](methods.md) - [Method Receiver](methods/receiver.md) + - [Construction](structs/struct-construction.md) - [Example](methods/example.md) - [Pattern Matching](pattern-matching.md) - [Destructuring Enums](pattern-matching/destructuring-enums.md) diff --git a/src/methods/receiver.md b/src/methods/receiver.md index 4c3f7e513a0a..9bed3eb04ae1 100644 --- a/src/methods/receiver.md +++ b/src/methods/receiver.md @@ -17,3 +17,11 @@ are other possible receivers for a method: Beyond variants on `self`, there are also [special wrapper types](https://doc.rust-lang.org/reference/special-types-and-traits.html) allowed to be receiver types, such as `Box`. + +
+ +* In reality, all functions in Rust are static. Receivers just add the "dot syntax" syntactic sugar by implicitly passing the struct by move, reference, or mutable reference. + +* You can explicitly call any of these methods with `StructName::method_name(&structure, /*the rest of the args*/)` + +
\ No newline at end of file diff --git a/src/structs/struct-construction.md b/src/structs/struct-construction.md new file mode 100644 index 000000000000..5d8c3bf2dcfd --- /dev/null +++ b/src/structs/struct-construction.md @@ -0,0 +1,43 @@ +# Construction + +Unlike in C++ or Java, there is no "constructor" in Rust for structs, all +construction is done using struct construction syntax. + +It is convention, however, to either implement the `Default` trait, or create a +method called `new` that has no receiver (i.e., a "static" function). + +```rust,editable +struct Person { + name: String, + age: u8, +} + +impl Person { + pub fn new(name: String, age: u8) -> Person { + Person { + name, + age + } + } + + pub fn new_birth(name: String) -> Person { + Self::new(name, 0) + } +} + +fn main() { + let peter = Person::new(String::from("Peter"), 23); + + println!("{} is {} years old", peter.name, peter.age); +} +``` + +
+ +* Mention the `Self` static scope accessor, it allows you to access any method of a struct. + +* 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, e.g., `Person::display(&peter)` if it had such a method `display(&self)`. + +* 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. + +
\ No newline at end of file