Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

rust - 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
}

Note that self is a Button and self.click_callback is an Option<Box<Fn(&mut Button)>>

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

This temporarily replaces click_callback with None, hence why you have to put it back when you're done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...