Implementation
Implementation
Inherent Implementation
Implementation
Trait Implementation
Generic Implementation
Trait bound impl
Blanket impl
đĻimpl block for a struct automatically gets access to the fields of that struct.thatâs why we used Instead of fn area(w:&width, h:&hight) || fn area(&self)
đĻRust impl mean define method / function for (struct/enum/trait)
Here we define the method for the struct/enum itself.
Here Point::new is like a constructor and distance_from_origin is an instance method.
struct Circle {
radius: f64,
}
impl Circle {
fn area(&self) -> f64 {
3.1416 * self.radius * self.radius
}
fn new(r: f64) -> Self {
Self { radius: r }
}
}
Use:
let c = Circle::new(5.0);
println!("Area = {}", c.area());
We directly write method for the struct and enum inherent
implementation.
Inherent Implementation
Trait Implementation
Generic Implementation
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
Used
let p1 = Point::new(10, 20);
let p2 = Point::new(1.1, 2.2);
impl<T> āĻŦā§āϝāĻŦāĻšāĻžāϰ āĻāϰāĻž āĻšā§ āϝāĻāύ struct/enum generic type āύā§ā§āĨ¤īŋŊ
impl<TypeParam> â āϏāĻŦ āĻāĻžāĻāĻĒā§āϰ āĻāύā§āϝ method define āĻšāĻŦā§
Generic Implementation
Unknown type in method
With Generic it can take any Unknown type in method
Generic + Trait Bound impl
use std::fmt::Display;
struct Wrapper<T>(T);
// Trait bound: T must implement Display
impl<T: Display> Wrapper<T> {
fn show(&self) {
println!("Value = {}", self.0);
}
}
Used:
let w = Wrapper(42);
w.show();
// works, āĻāĻžāϰāĻŖ i32 implements Display
Trait Bound impl
Trait bound means you are giving a condition âT: Display
âThis method/function will only work on types that implement Display trait.â
Blanket impl
[ Rule ]
[ Purpose ]
trait Greet {
fn greet(&self);
}
impl<T: ToString> Greet for T {
fn greet(&self) {
println!("Hello, {}", self.to_string());
}
}
Using impl<T: Trait> allows you use multiple types at once.
Used:
"Rust".greet();
123.greet();
Blanket impl
Using impl<T: Trait> allows you use multiple types at once.
Blanket Impl = Implementing a trait for all applicable types at once.