π§Deref Coercion
What is Deref Coercion?
Deref Coercion?When the Deref Coercion is applied?
Deref Coercion is applied?Cases
How it works?
Deref with Function & Method Calls
Deref with Function & Method Callsuse std::ops::Deref;
#[derive(Debug)]
struct MySmartPointer<T>(T);
impl<T> MySmartPointer<T> {
fn new(x: T) -> MySmartPointer<T> {
MySmartPointer(x)
}
}
impl<T> Deref for MySmartPointer<T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
fn say_hi(name: &str) {
println!("Hi, {name}!")
}
fn main() {
let name = MySmartPointer::new(String::from("Thomas"));
println!("name = {:?}", name); // Outputs: name = MySmartPointer(5)
println!("name = {}", *name); // Outputs: name = 5
say_hi(&name); // Outputs: Hi, Thomas!
}
DerefMut for Mutable Dereferencing
DerefMut for Mutable DereferencingLast updated