Welcome to this in-depth guide on Rust, where we delve into the fascinating world of the Self keyword! š
In Rust, the self keyword is a placeholder for the current instance of a struct or trait object. It allows you to access the fields and methods defined within the struct or trait.
struct Person {
name: String,
age: u32,
}
impl Person {
fn display_age(&self) {
println!("{} is {}", self.name, self.age);
}
}
let john = Person { name: String::from("John"), age: 30 };
john.display_age(); // Output: John is 30š Note: The self keyword is similar to this in languages like Java or JavaScript.
When defining methods within a struct, self is used to access the struct's fields.
struct Point {
x: f32,
y: f32,
}
impl Point {
fn distance_from_origin(&self) -> f32 {
(self.x.pow(2) + self.y.pow(2)).sqrt()
}
}
let origin = Point { x: 0.0, y: 0.0 };
let point = Point { x: 3.0, y: 4.0 };
println!("Distance from origin: {}", point.distance_from_origin()); // Output: 5.0Traits in Rust allow you to define common behavior for multiple types. When implementing a trait, you can use self to access the data and methods of the implementing type.
trait Drawable {
fn draw(&self);
}
struct Rectangle {
width: u32,
height: u32,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
}
}
let rectangle = Rectangle { width: 10, height: 5 };
rectangle.draw(); // Output: Drawing a rectangle with width 10 and height 5It's essential to understand that self is a mutable reference by default. This means you can modify the struct's fields within the method.
struct Person {
name: String,
age: u32,
}
impl Person {
fn change_name(&mut self, new_name: &str) {
self.name = String::from(new_name);
}
}
let mut john = Person { name: String::from("John"), age: 30 };
john.change_name("Jane");
println!("{}'s name has been changed to {}", john.name, john.name);You can create an immutable reference to self by prefixing it with & in the method signature. This prevents the struct's fields from being modified within the method.
struct Person {
name: String,
age: u32,
}
impl Person {
fn name(&self) -> &String {
&self.name
}
}
let john = Person { name: String::from("John"), age: 30 };
let name = john.name();
println!("Name is {}", name);What is the purpose of the `self` keyword in Rust?
Now that you've grasped the basics of using the self keyword in Rust, you're well on your way to mastering this powerful language. Keep practicing, and happy coding! š
Remember to come back to CodeYourCraft for more in-depth tutorials and resources to help you level up your Rust skills! š¤
š Note: Stay tuned for our next tutorial where we'll dive deeper into Rust's ownership and borrowing system!
By following this tutorial, you've learned about:
Practice the quiz and keep exploring CodeYourCraft for more insights on Rust! š