gpt4 book ai didi

callback - 奇怪的回调调用语法(需要解释)

转载 作者:行者123 更新时间:2023-11-29 08:18:19 25 4
gpt4 key购买 nike

以下示例是我发现的一个最小示例,可以解释我遇到的问题:

use std::borrow::BorrowMut;
use std::ops::DerefMut;

#[derive(Debug, Clone)]
enum ConnectionState {
NotStarted,
}

type StateChangedCallback = Box<FnMut(ConnectionState) + Send + Sync>;

fn thread_func(mut on_state_changed: StateChangedCallback) {
let new_state = ConnectionState::NotStarted;
let f: &mut BorrowMut<StateChangedCallback> = &mut on_state_changed;
f.borrow_mut().deref_mut()(new_state);
}

fn main() {
let on_state_changed = Box::new(|new_state| {
println!("New state: {:?}", new_state);
});

let join_handle = std::thread::spawn(|| thread_func(on_state_changed));

join_handle.join().unwrap();
}

我有一个简单的线程,需要调用从 main 传递的回调。回调就是签名Box<FnMut(ConnectionState) + Send + Sync> ,因为我想多次调用它。我设法调用回调的唯一方法是使用这种奇怪的语法:

let f: &mut BorrowMut<StateChangedCallback> = &mut on_state_changed;
f.borrow_mut().deref_mut()(new_state);

我搜索了一下,没有找到合理的解释。我做错了什么?或者这就是 Rust 的工作方式吗?

如果是这样,有人可以解释这种语法的原因吗?

最佳答案

你把事情复杂化了。

您可能会解释为什么您认为您必须执行 borrow_mut(),因为您的签名中不涉及借用。

您的函数 thread_func 可以简化为:

fn thread_func(mut on_state_changed: StateChangedCallback) {
let new_state = ConnectionState::NotStarted;
on_state_changed(new_state);
}

请注意,与您的句子“我想多次调用它(回调)”相反,您不能这样做,因为您将闭包移到了函数中。

关于callback - 奇怪的回调调用语法(需要解释),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53262644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com