Cannot borrow `write` as mutable, as it is a captured variable in a `Fn` closure

Hi, I am trying to create a websocket connection. And once when the connection is created successfully, based on some event change in UI, I am trying to send request to the server. So when user clicks a button in UI, my event listener "request" will be getting triggered. At that time, I'm getting this error.

Code:

#[tokio::main]
async fn main() {
        let url = url::Url::parse("wss://127.0.0.1:8000/ws").unwrap();   
        
        println!("Creating connection"); 
        let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");        
        println!("WebSocket handshake has been successfully completed \n"); 
        println!("ws_stream type: ");
        print_type_of(&ws_stream);      

  tauri::Builder::default()  
  .setup(move |app|{
    let (mut write, read) = ws_stream.split(); 
    app.listen_global("request", move |_handler|{
        println!("Sending the request to server");
        write.send(Message::Text(r#"{
            "reqid": 42
        }"#.to_string()+"\n"));
        println!("Request sent!!!");
    });
  Ok(())
})
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}```

Error:

error[E0596]: cannot borrow write as mutable, as it is a captured variable in a Fn closure
--> src\main.rs:32:9
|
32 | / write.send(Message::Text(r#"{
33 | | "type": "getConfig",
34 | | "envelope": {
35 | | "scope": ["navigation"],
36 | | "content" : ["all"]
37 | | }
38 | | }"#.to_string()+"\n"));
| |______________________________^ cannot borrow as mutable

Closures capture their environment - the Fn trait expects its arguments by reference, not by mutable reference. This means you cannot use a mutable reference (in your case write) within the closure, if the mutable reference is defined outside. You need interior mutability here to solve this problem. This means wrapping your mutable reference within a special type, that can be shared via an immutable reference, but still allows mutability of its inner value.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.