繁体   English   中英

Rust 作为结构方法的闭包

[英]Rust closure as a method of struct

我怎样才能调用一个接收我的结构作为参数并将该闭包作为成员的闭包?

type Thunk = Box<dyn FnMut(&mut Config) + Send + 'static>;

struct Config {
    s: String,
    f: Thunk,
}

impl Config {
    fn run(&mut self) {
        // the problem is here
        (self.f)(self);
    }
}

fn main() {
    let cfg = Config {s: String::from("hello"), f: Box::new( |c| {
        println!("{}", c.s);
    }) };
}
error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:11:18
   |
11 |         (self.f)(self);
   |         -------- ^^^^ second mutable borrow occurs here
   |         |
   |         first mutable borrow occurs here
   |         first borrow later used by call

这通常是不可能的,由于 Rust 安全规则 - 回调在调用期间专门借用自己,因此您不能同时再次借用整个结构。

要了解为什么这不仅仅是一个理论问题,请考虑以下问题:

type Thunk = Box<dyn FnMut(&mut Config) + Send + 'static>;

struct Config {
    s: String,
    f: Thunk,
}

impl Config {
    fn run(&mut self) {
        // the problem is here
        (self.f)(self);
    }
}

fn main() {
    let s = String::from("temporary");
    let cfg = Config {s: String::from("hello"), f: Box::new(move |c| {
        c.f = Box::new(|_| {});
        println!("{}", s);
    }) };
}

在这段代码中,我们有回调,它在运行时本质上会自行删除。 由于它通过移动捕获s ,因此s与回调一起被丢弃。 然后回调尝试打印s - 如果允许的话,我们就有了一个释放后使用。


解决方案将取决于实际要求。 go 的最简单方法是分离配置,仅将不包含Thunk本身的部分传递给Thunk

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM