奇怪的回调调用语法(需要解释)
Weird callback call syntax (need explanation)
以下示例是我发现的一个最小示例,可以解释我遇到的问题:
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);
}
请注意,与你的句子 "I want to call it (the callback) multiple times" 相反,你不能这样做,因为你将闭包移到了函数中。
以下示例是我发现的一个最小示例,可以解释我遇到的问题:
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);
}
请注意,与你的句子 "I want to call it (the callback) multiple times" 相反,你不能这样做,因为你将闭包移到了函数中。