Rust :: Pointers

Pointers

Raw Pointers

Smart Pointers

Deref and DerefMut Traits

pub trait Deref {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

pub trait DerefMut: Deref {
    fn deref_mut(&mut self) -> &mut Self::Target;
}

Drop trait

pub trait Drop {
    fn drop(&mut self);
}
// drop method is to take ownership and does nothing with it
fn drop<T>(_x: T) { }

// self.drop() cannot be called explicitly
// use std::mem:drop(instance) isntead
impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}

Common Smart Pointers

Box

// to Point to Data on the Heap
let b = Box::new(5);

// Recursive Types
// cons list
enum List {
    Cons(i32, Box<List>),
    Nil,
}
let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));

// Err
// dyn: dynamic
Box<dyn std::error::Error>

// use box to wrap differnt types
let range = if first < last {
    Box::new(first..last) as Box<dyn Iterator<Iterm = _>>
else {
    Box::new((last..first).rev())
}

Rc

enum List {
    Cons(i32, Rc<List>),
    Nil,
}
use crate::List::{Cons, Nil};
use std::rc::Rc;
fn main() {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    // Rc::clone() does not do deep copy; but increase ref count
    let b = Cons(3, Rc::clone(&a));
    let c = Cons(4, Rc::clone(&a));
    Rc::strong_count(&a);   // 3
}