我有一个闭包,它可以改变在它之外设计的变量。我将如何调用这个从异步范围内修改状态的闭包?
我有以下代码(摘要,以显示问题):
#[tokio::main]
async fn main() {
let mut y = false;
let mut incr = |z: bool| {
y = z;
};
stream::iter(0..1).for_each(|_| async {
incr(true);
}).await;
});
产生以下内容:
error: captured variable cannot escape `FnMut` closure body
--> src/main.rs:40:37
|
36 | let mut incr = |z: bool| {
| -------- variable defined here
...
40 | stream::iter(0..1).for_each(|_| async {
| ___________________________________-_^
| | |
| | inferred to be a `FnMut` closure
41 | | incr(true);
| | ---- variable captured here
42 | | }).await;
| |_____^ returns an `async` block that contains a reference to a captured variable, which then escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
现在,我相信我明白为什么会发生错误。我只是想不出办法解决这个问题。
对于上下文:
- 我有一个 websocket 客户端,我正在从流中读取
- 每次我从流中接收数据时,我都会对其进行转换
- 然后,我需要使用转换后的数据调用闭包,以便在其他地方使用——本质上就像 JavaScript 中的 EventEmitter。
我会以错误的方式解决这个问题吗?我是一名 JavaScript 开发人员,所以我不得不在这里改变我的思维方式。