Treating Smart Pointers Like Regular References
The Deref trait lets smart pointers behave like references. When a type
implements Deref, you can use the * operator to access its inner value, and
Rust's deref coercions apply automatically.
Implementing Deref
Here is a simple smart pointer that wraps a value:
public struct MyBox<T> {
value: T,
}
extension MyBox<T> {
public static fn new(value: T): MyBox<T> {
MyBox { value }
}
}
extension MyBox<T>: Deref {
type Target = T
fn deref(): &T {
&self.value
}
}
Deref Coercions
Once Deref is implemented, Oxide can coerce references for you:
fn greet(name: &str) {
println!("Hello, \(name)")
}
fn main() {
let name = MyBox.new(String.from("Oxide"))
// Manual deref
greet(&*name)
// Deref coercion
greet(&name)
}
Deref coercions make APIs ergonomic while still keeping explicit ownership and borrowing rules.