去掉你的初始代码
pub fn new(context: Arc<Context>) -> Arc<Button> {
let clickable = Clickable::new(context.clone());
let button = Arc::new(Button{
context: context,
clickable: clickable.clone(),
});
let tmp_callback = Box::new(|| {
button.do_stuff();
});
clickable.set_callback(Some(tmp_callback));
button
}
error[E0373]: closure may outlive the current function, but it borrows `button`, which is owned by the current function
--> src/main.rs:101:37
|
101 | let tmp_callback = Box::new(|| {
| ^^ may outlive borrowed value `button`
102 | button.do_stuff();
| ------ `button` is borrowed here
|
help: to force the closure to take ownership of `button` (and any other referenced variables), use the `move` keyword, as shown:
| let tmp_callback = Box::new(move || {
注意
help
在底部,您需要使用
move
new
函数结束时
button
let tmp_callback = Box::new(|| {
到
let tmp_callback = Box::new(move || {
error[E0382]: use of moved value: `button`
--> src/main.rs:107:9
|
102 | let tmp_callback = Box::new(move || {
| ------- value moved (into closure) here
...
107 | button
| ^^^^^^ value used here after move
|
= note: move occurs because `button` has type `std::sync::Arc<Button>`, which does not implement the `Copy` trait
这里的错误可能更清楚一些。您试图转移
而且
在身体内部使用
可以
取得所有权。然后你会想要改变
let tmp_callback = Box::new(move || {
button.do_stuff();
let button_clone = button.clone();
let tmp_callback = Box::new(move || {
button_clone.do_stuff();
现在你已经创建了一个新的
Button
对象,并返回
Arc
对于对象本身,同时也给予第二个
弧
回调本身。
使现代化
鉴于您的评论,这里确实存在循环依赖性问题,因为您的
Clickable
对象拥有对的引用的所有权
按钮
按钮
可点击
让button\u clone=按钮。克隆();
按钮克隆。do_stuff();
let button_weak = Arc::downgrade(&button);
let tmp_callback = Box::new(move || {
if let Some(button) = button_weak.upgrade() {
button.do_stuff();
}
});
所以
按钮
,如果
不再引用,则回调将为no-op。
你可能还想考虑
clickables
Weak