From e1d31b3d17f6d11f9ee7cfe2f86460e14667af1f Mon Sep 17 00:00:00 2001 From: saltukalakus Date: Thu, 31 Oct 2024 23:03:58 +0000 Subject: [PATCH] Self --- src/SUMMARY.md | 1 + src/essentials/self.md | 83 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 src/essentials/self.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index aee89fa..3853cb1 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -9,6 +9,7 @@ - [Features Compilation](./essentials/features-compilation.md) - [![no_std] Attribute](./essentials/no-std.md) - [Traits](./essentials/trait.md) + - [Self Keyword](./essentials/self.md) - [Patterns](./patterns.md) - [Behavioral Patterns](./patterns/behavioral.md) diff --git a/src/essentials/self.md b/src/essentials/self.md new file mode 100644 index 0000000..99bcec8 --- /dev/null +++ b/src/essentials/self.md @@ -0,0 +1,83 @@ +### Is **self** a special keywork in Rust? + +**self** is a special keyword in Rust. It is used to refer to the instance of the struct or enum within its associated methods. It is similar to this in other object-oriented languages like Java or C++. + +### Usage of self + +**Method Definitions**: When defining methods for a struct or enum, self is used to refer to the instance on which the method is called. + +**Method Parameters**: self can be used as a parameter in method definitions to indicate that the method takes ownership, borrows immutably, or borrows mutably from the instance. + +### Immutable Borrow (&self) + +When a method takes &self as a parameter, it means the method borrows the instance immutably. + +```rust +pub struct Person { + name: String, +} + +impl Person { + // Method that borrows the instance immutably + fn greet(&self) { + println!("Hello, my name is {}!", self.name); + } +} + +fn main() { + let person = Person { + name: String::from("Alice"), + }; + person.greet(); // Calls the greet method +} +``` + +### Mutable Borrow (&mut self) + +When a method takes &mut self as a parameter, it means the method borrows the instance mutably. + +```rust +pub struct Counter { + count: i32, +} + +impl Counter { + // Method that borrows the instance mutably + fn increment(&mut self) { + self.count += 1; + } +} + +fn main() { + let mut counter = Counter { count: 0 }; + counter.increment(); // Calls the increment method + println!("Count: {}", counter.count); + counter.increment(); // Calls the increment method + println!("Count: {}", counter.count); +} +``` + +### Ownership (self) + +When a method takes self as a parameter, it means the method takes ownership of the instance. + +```rust +pub struct Person { + name: String, +} + +impl Person { + // Method that takes ownership of the instance + fn into_name(self) -> String { + self.name + } +} + +fn main() { + let person = Person { + name: String::from("Alice"), + }; + let name = person.into_name(); // Calls the into_name method, taking ownership + println!("Name: {}", name); +} +``` \ No newline at end of file