[英]Error on Future generator closure: Captured variable cannot escape `FnMut` closure body
[英]rust error: captured variable cannot escape `FnMut` closure body
以下代碼嘗試在通過連接獲取msg
后異步更新主 dataframe df
(來自 polars 包)。
我已經看到關於堆棧溢出的“重復”帖子,但仍然不明白我做錯了什么。 我只是想可變地借用dataframe並更新它,僅此而已,我用字符串試了一下。 它工作得很好......
pub async fn new_handler(endpoint: &str) -> tokio::task::JoinHandle<()> {
// Make master df for this handler
let mut df = DataFrame::empty().lazy();
// Make a stream for this handler
let stream = new_stream(endpoint).await;
let handle = tokio::spawn(async move {
// let handle = tokio::spawn(async {
stream
.for_each(|msg| async move {
match msg {
Ok(msg) => {
// Parse the json message into a struct
let jsonmsg: AggTrade =
serde_json::from_str(&msg.to_string()).expect("Failed to parse json");
let s0 = Series::new(
"price",
vec![jsonmsg.price.parse::<f32>().expect("Failed to parse price")],
);
let s1 = Series::new(
"quantity",
vec![jsonmsg
.quantity
.parse::<f32>()
.expect("Failed to parse quantity")],
);
// Create new dataframe from the json data
let df2 = DataFrame::new(vec![s0.clone(), s1.clone()]).unwrap().lazy();
// append the new data from df2 to the master df
df = polars::prelude::concat([df, df2], false, true)
.expect("Failed to concat");
}
Err(e) => {
println!("Error: {}", e);
}
}
})
.await
});
handle
}
我收到以下錯誤:
error: captured variable cannot escape `FnMut` closure body
--> src/websockets.rs:33:29
|
27 | let mut df = DataFrame::empty().lazy();
| ------ variable defined here
...
33 | .for_each(|msg| async {
| ___________________________-_^
| | |
| | inferred to be a `FnMut` closure
34 | | match msg {
35 | | Ok(msg) => {
36 | | // Parse the json message into a struct
... |
58 | | df = polars::prelude::concat([df.clone(), df2.clone()], false, true)
| | -- variable captured here
... |
86 | | }
87 | | })
| |_____________^ 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
問題是傳遞給stream.for_each()
的閉包可以被多次調用,但是df
變量在被df.clone()
調用引用時被移動到閉包中。
這是一個獨立的最小代碼示例,顯示了相同的編譯錯誤。 如果取消注釋 function 中的最后幾行,它將無法編譯:
async fn fails_moved_into_closure_called_multiple_times() {
println!("fails_moved_into_closure_called_multiple_times():");
let mut df = vec![];
let closure = || async move {
let new_value = df.len();
println!("in the closure, pushing {}", new_value);
df.push(new_value);
};
let future = closure();
future.await;
let future2 = closure(); // FAIL
future2.await;
println!("final value: {:?}", df); // FAIL
}
其實 Rust 不能確定你的for_each
function 不會在多線程中多次並發調用閉包。 這是一個使用Arc<Mutex<T>>
的解決方案,它是線程安全的並修復了所有權問題:
async fn fix_using_arc() {
println!("fix_using_arc():");
let df = Arc::new(Mutex::new(vec![]));
let closure = || async {
let my_df = Arc::clone(&df);
let mut shared = my_df.lock().unwrap();
let new_value = shared.len();
println!("in the closure, pushing {}", new_value);
shared.push(new_value);
};
let future = closure();
future.await;
let future2 = closure();
future2.await;
println!("final value: {:?}", df);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.