impl) in Rust TutorialWelcome back to CodeYourCraft, where we're diving deep into the world of Rust programming! Today, we're going to learn about Method Syntax using the impl keyword.
šÆ Key Takeaways
impl keyword for defining methodsMethods are functions that are associated with a specific type. They provide a way to interact with the data of that type. In Rust, methods can be defined using the impl keyword.
impl Keyword š”The impl keyword is used to define methods for a specific type. It tells the Rust compiler that the following block of code defines the methods for a certain type.
struct MyStruct {
value: i32,
}
impl MyStruct {
fn new(value: i32) -> Self {
MyStruct { value }
}
fn double(&mut self) {
self.value *= 2;
}
}In the example above, we have defined a new struct called MyStruct and used the impl keyword to define methods for it. The new method is a constructor method that takes an i32 as an argument and returns a new instance of MyStruct. The double method doubles the value of an existing MyStruct instance.
Instance methods are methods that are called on an instance of a struct or enum. They require an instance to be passed as the first argument using the self keyword.
fn main() {
let my_struct = MyStruct::new(5);
my_struct.double();
println!("MyStruct value: {}", my_struct.value);
}In the example above, we have created an instance of MyStruct using the new method and called the double method on it. The double method modified the value field of MyStruct.
Static methods are methods that can be called without an instance of a struct or enum. They don't require a self argument.
impl MyStruct {
fn total(values: Vec<i32>) -> i32 {
values.iter().sum()
}
}
fn main() {
let values = vec![1, 2, 3, 4];
let total = MyStruct::total(values);
println!("Total: {}", total);
}In the example above, we have defined a static method total for MyStruct that takes a vector of i32 as an argument and returns the sum of its elements. We can call this method without creating an instance of MyStruct.
What is the purpose of the `impl` keyword in Rust?
Remember to practice what you've learned by trying out some exercises on your own! Stay tuned for more in-depth Rust tutorials at CodeYourCraft. Happy coding! ššš