金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
# Rust callback idiom

Code is from: https://stackoverflow.com/questions/41081240/idiomatic-callbacks-in-rust
and
https://morestina.net/blog/793/closure-lifetimes-in-rust

```
struct Processor<'a> {
    callback: Box<dyn FnMut() + 'a>,
}

impl<'a> Processor<'a> {
    fn new() -> Processor<'a> {
        Processor {
            callback: Box::new(|| ()),
        }
    }

    fn set_callback(&mut self, c: impl FnMut() + 'a) {
        self.callback = Box::new(c);
    }

    fn process_events(&mut self) {
        (self.callback)();
    }
}

fn simple_callback() {
    println!("hello");
}

fn main() {
    let _ = Processor::new();
    
    let mut p = Processor {
        callback: Box::new(simple_callback),
    };
    p.process_events();
    let s = "world!".to_string();
    let callback2 = move || println!("hello {}", s);
    p.set_callback(callback2);
    p.process_events();
}
```

Note:
* "impl FnMut()" can only used in function declaration, not in struct declaration.
* dyn FnMut() is unsized, so it must be stored in Box
* set_callback(&mut self, c: impl FnMut()) need a lifetime for c to tell compiler that c outlives structure
    + rustc suggests `impl FnMut() + 'static`, but that is too restrictive
        - In most cases, we do not have a static lifetimed callback
* FnMut() is more restrictive than FnOnce(), but FnOnce() can only be called once
* set_callback(...) is a template method, because each closure has a different type
posted on 2021-08-24 10:19 金庆 阅读(250) 评论(0)  编辑 收藏 引用 所属分类: 8. Rust

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理