如何将参数传递给存储回调?

问题描述 投票:-2回答:1

给定一个“代表”结构,有一个“处理程序”的成员,我怎么可以用动态字符串调用的处理?

pub struct Processor {
    callback: Box<FnMut()>,
    message: Option<String>
}

impl Processor {
    pub fn new<CB: 'static + FnMut()>(c: CB) -> Self {
        Processor {
            callback: Box::new(c),
            message: Some("".into())
        }
    }

    pub fn set_callback<CB: 'static + FnMut(&str)>(&mut self, callback: CB) {
        self.callback = Box::new(callback);
    }

    pub fn set_message<S>(&mut self, message: S) where S: Into<String> {
        self.message = Some(message.into());
    }

    pub fn process(&mut self) {
        match self.message {
            Some(string) => {
                if self.message.chars().count() > 0 {
                    (self.callback)(self.message);
                } else {
                    (self.callback)();
                }
            },
            None => {}
        }
    }
}

impl EventEmitter {
    pub fn new() -> Self {
        EventEmitter {
            delegates: Vec::new()
        }
    }

    /// Register an Event and a handler
    pub fn on(&mut self, event: Event, handler: Processor) {
        self.delegates.push(Delegate::new(event, handler))
    }

    /// Run handlers on the emitted event
    pub fn emit(&mut self, name: &'static str/*, with message!! */) {
        for delegate in self.delegates.iter_mut(){
            if delegate.event.name == name {
                delegate.handler.process();
            }
        }
    }

    /// Run handlers on the emitted event
    pub fn emit_with(&mut self, name: &'static str, message: &'static str) {
        for delegate in self.delegates.iter_mut() {
            if delegate.event.name == name {
                delegate.handler.set_message(message);
                delegate.handler.process();
            }
        }
    }
}

再后来,我有:

emitter.on(
    Event::new("TEST"), 
    Processor::new(|x| println!("Test: {}", x))
);
emitter.emit_with("TEST", "test");

但是,编译器会抱怨:

  --> src/main.rs:97:3
   |
97 |         Processor::new(|x| println!("Test: {}", x))
   |         ^^^^^^^^^^^^^^ --- takes 1 argument
   |         |
   |         expected closure that takes 0 arguments

如果删除了“&STR”类型参数的set_callback()的定义:

set_callback<CB: 'static + FnMut()>(&mut self, callback: CB)

我能得到这个使用封闭,不带任何参数的工作:

emitter.on( // emitter.emit("TEST");
    Event::new("TEST"), 
    Processor::new(|| println!("static string."))
);

有没有办法通过一个字符串能够最终被传递给处理程序的emit_with()函数?

rust
1个回答
1
投票

在这里,你已经写了:

pub struct Processor {
    callback: Box<FnMut(/* RIGHT HERE */)>,
    message: Option<String>
}

你已经宣布FnMut(封闭),不带任何参数。语法是FnMut(/* arguments to closure */),但你没有提供任何。因此,你不能传递一个闭包确实需要的参数。你不能有一个闭包,这两个带有参数,并在同一时间不带参数。

此外,您使用的FnMut(&str),但只在一个地方。你需要它的所有地方。既然你想通过或不通过字符串,我把它转换成一个Optional<&str>(使得封闭类型是FnMut(Option<&str>))。

我已经修改了你的代码,这样闭合带有一个可选的&str。这就是我建议你处理这个问题:

pub struct Processor {
    // The closure takes an optional string.
    callback: Box<FnMut(Option<&str>)>,
    message: Option<String>
}

impl Processor {
    pub fn new<CB: 'static + FnMut(Option<&str>)>(c: CB) -> Self {
        Processor {
            callback: Box::new(c),
            message: Some("".into())
        }
    }

    pub fn set_callback<CB: 'static + FnMut(Option<&str>)>(&mut self, callback: CB) {
        self.callback = Box::new(callback);
    }

    pub fn set_message<S>(&mut self, message: S) where S: Into<String> {
        self.message = Some(message.into());
    }

    pub fn process(&mut self) {
        match self.message {
            Some(string) => {
                // NOTE: Instead of .chars().count > 0
                if !self.message.is_empty() {
                    (self.callback)(Some(self.message));
                } else {
                    (self.callback)(None);
                }
            },
            None => {}
        }
    }
}

注意:这是未经测试,但也许应该工作。如果任何错误上来,做评论。

© www.soinside.com 2019 - 2024. All rights reserved.