What's the correct way to implement the equivalent of multiple mutable (statically allocated, statically dispatched, etc.) callbacks in Rust?

此生再无相见时 提交于 2019-11-28 14:25:54

One way is to use a RefCell, which allows you to mutate things with only &Pen instead of &mut Pen, at the cost of pushing the borrow-checking to runtime. It’s very cheap: there is no allocation, just a single flag test. The main downside is that violating the rules will result in a panic at runtime. A useful rule of thumb is to never borrow for any longer than necessary (think of them as “single-threaded mutexes”).

use std::cell::RefCell;

fn main() {
    println!("Hello, world !");

    let p1 = RefCell::new(Pen::new());
    {
        let mut rp1 = p1.borrow_mut();
        rp1.write("Hello");
        println!("ink: {}, color: {}", rp1.ink, rp1.color_cmyk);
    }

    let cb = |text| {
        if p1.borrow_mut().write(text) {
            println!("{}", text);
        }
        else {
            println!("Out of ink !");
        }
    };

    let cb2 = |text| {
        let mut rp1 = p1.borrow_mut();
        rp1.write(text);
        rp1.ink
    };

    cb("Hello");
    cb("World");
    println!("{}", cb2("Hello"));
}

Another way is to set up the callback system to pass in the object that you’re modifying as an argument. The trade-off is then your callback system needs to be aware of this state.

fn main() {
    println!("Hello, world !");

    let mut p1 = Pen::new();
    p1.write("Hello");
    println!("ink: {}, color: {}", p1.ink, p1.color_cmyk);

    let cb = |p1: &mut Pen, text| if p1.write(text) {
        println!("{}", text);
    } else {
        println!("Out of ink !");
    };

    let cb2 = |p1: &mut Pen, text| {
        p1.write(text);
        p1.ink
    };

    cb(&mut p1, "Hello");
    cb(&mut p1, "World");
    println!("{}", cb2(&mut p1, "Hello"));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!