rust unsafe

· 329 words · 1 minute read
fn main() {
    let mut d = String::from("aaaa");
    let d_len = d.len();
    { // 去掉 or 不去掉
        let mut e = String::wtih_capacity(d_len);
        unsafe {
            // 两个指针指向相同的堆内存d
            ptr::copy(&d, &mut e, 1);
        };
        println!("{:?}", e.as_ptr());
        mem::drop(e);
    }
    println!("{:?}", d.as_ptr());
    d.push_str("a");
    println!("{:?}", d)
}

设计模式 🔗

设计模式: 常见的责任链,策略,装饰器模式
在rust标准库中经常使用的适配器和迭代器模式

责任链模式 🔗

trait Handler<'a> {
    fn set_next(&mut self, next: &'a dyn Handler<'a>);
    fn hanlde(&self, msg: &str);
}
struct AHandler<'a> {
    next: Option<&'a dyn Handler<'a>>,
}

策略模式 🔗

trait Strategy {
    fn do();
}

impl Strategy for A{}
impl Strategy for B{}
struct C {
    strategy: Box<dyn Strategy>,
}
impl C {
    fn do_strategy(&self) {
        self.strategy.do();
    }
    fn set_strategy(&mut self, strategy: Box<dyn Stragety>) {
        self.strategy = strategy;
    }
}

装饰器模式 🔗

trait Component {
    fn operate(&self) -> String; 
}
trait Decorator: Component {
    fn new(component: Box<dyn Component>) -> Self;
}
struct A {
    component: Box<dyn Component>,
}

impl Decorator for A {
    fn new(component: Box<dyn Component>) -> Self {
        Self {component}
    }
}

impl Component for A {
        fn operate(&self) -> String {
            format!("decorator: {}", self.component.operate())
        }
}

迭代器与适配器模式 🔗

trait Iterator<T> {
    fn next(&mut self) -> Option<T>;
}
struct container<T> {
    data: Vec<T>,
}
struct containerIter<'a, T> {
    index: usize,
    container: &'a container<T,
}
impl container {
    fn iter(&self) -> containerIter {
        containerIter{
            index: 0,
            container: &self,
        }
    } 
}

impl<T> Iterator<T> for containerIter{
    fn next(&mut self) -> Option<T> {
        let item = self.container.data.get(self.index).cloned();
        self.index += 1;
        item
    }
}