由于双重借用,无法将 self 作为回调参数传递 [英] Cannot pass self as callback parameter due to double borrowing
问题描述
我正在尝试调用保存在结构中的闭包,但我也想将该结构作为参数传递给闭包.这是具体的一段代码.
I'm trying to call closure that was saved inside a struct but I'd also like to pass the struct as an argument to the closure. Here's the specific piece of code.
pub fn react(&mut self) -> &mut Button {
if let Some(ref mut c) = self.click_callback {
c(self);
}
self
}
注意 self 是一个 Button
而 self.click_callback
是一个 Option
Note that self is a Button
and self.click_callback
is an Option<Box<Fn(&mut Button)>>
因此,根据我的理解,if let"借用 self 直到其作用域结束,但是当我尝试将 self 作为参数传递时,它会尝试再次借用它.我可以做些什么来避免这种双重借用尝试?
So from what I understand the "if let" borrows self until its scopes ends, but then when I try to pass self as an argument it attempts to borrow it again. Is there anything specific I can do that will avoid this double borrow attempt?
推荐答案
最简单的解决方案是将回调从 self
中分离出来,如下所示:
The simplest solution is to break the callback out from self
, like so:
let callback = self.click_callback.take();
if let Some(ref mut c) = callback {
c(self);
}
self.click_callback = callback;
self
这会暂时将 click_callback
替换为 None
,因此您必须在完成后将其放回原处.
This temporarily replaces click_callback
with None
, hence why you have to put it back when you're done.
这篇关于由于双重借用,无法将 self 作为回调参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!