57 lines
1.1 KiB
Rust
57 lines
1.1 KiB
Rust
use std::ops::Deref;
|
|
use std::mem::drop;
|
|
|
|
struct MyBox<T>(T);
|
|
|
|
impl<T> MyBox<T> {
|
|
fn new(x: T) -> MyBox<T> {
|
|
MyBox(x)
|
|
}
|
|
}
|
|
|
|
impl<T> Deref for MyBox<T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &T {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
struct CustomSmartPointer {
|
|
data: String,
|
|
}
|
|
|
|
impl Drop for CustomSmartPointer {
|
|
fn drop (&mut self) {
|
|
println!("Dropping CustomSmartPointer with data `{}`!", self.data);
|
|
}
|
|
}
|
|
|
|
fn hello(name: &str) {
|
|
println!("Hello, {}!", name);
|
|
}
|
|
|
|
fn main() {
|
|
let x = 5;
|
|
let y = MyBox::new(x);
|
|
|
|
assert_eq!(5, x);
|
|
assert_eq!(5, *y);
|
|
|
|
// Deref trait
|
|
let m = MyBox::new(String::from("Rust"));
|
|
hello(&m); // hello(&(*m)[..]); without deref coercions
|
|
|
|
// Drop trait
|
|
let c = CustomSmartPointer { data: String::from("my stuff") };
|
|
println!("CustomSmartPointer created.");
|
|
|
|
// Manual early "destruction" with std::mem::drop, instead of
|
|
// automatic cleanup via the Drop trait
|
|
drop(c);
|
|
|
|
println!("CustomSmartPointer dropped before the end of main.");
|
|
let _d = CustomSmartPointer { data: String::from("other stuff") };
|
|
println!("CustomSmartPointer created.");
|
|
}
|