Why does the lines after loop block is not getting executed and remains unreachable?

Here I am trying to read the response received from the server inside a loop, so once when the loop ends I'm trying to print the entire response. While trying that I'm getting a warning message "any code following this expression is unreachable" and the remaining lines are not getting executed. Can someone suggest any solution for this?

Code:

#[tokio::main]
async fn main() {
    let (mut socket, response) =
    connect(Url::parse("wss://127.0.0.1:8080/ws").unwrap()).expect("Failed to connect");       
      
    tauri::Builder::default()  
    .setup(move |app|{
        let stream = Mutex::new(socket);
        app.listen_global("request", move |_handler| {  
        let mut response_data = vec![];
  
        let mut data = stream.lock().unwrap();
        data.write_message(Message::Text(r#"{
            "type": "config",
        }"#.to_string()+"\n")).unwrap();

      println!("Request sent");

      let result = loop {
          let msg = data.read_message().expect("Error reading message");
          println!("Received response: {}", msg);
          println!("\n");
          response_data.push(msg);
      };
      println!("\n\n");
      println!("Final Response : \n");
      println!("{:?}", response_data);
      });
    Ok(())
    })
    .run(tauri::generate_context!())
    .expect("error while running tauri application");
}

Warning:

warning: unreachable statement
  --> src\main.rs:41:7
   |
35 |         let result = loop {
   |  ____________________-
36 | |           let msg = data.read_message().expect("Error reading message");
37 | |           println!("Received response: {}", msg);
38 | |           println!("\n");
39 | |           response_data.push(msg);
40 | |       };
   | |_______- any code following this expression is unreachable
41 |         println!("\n\n");
   |         ^^^^^^^^^^^^^^^^ unreachable statement
   |

When would the code exit the loop?

loop is an infinite loop construct, and you never explicitly break out of it, so what else would you expect?

1 Like

The loop has to exit once when there is no message that needs to be read from the server.

What line of code in the loop will cause that to happen?

Actually I'm not sure on that part. Can someone suggest a solution for it.

You want to add the word break somewhere inside that loop {}. Exactly where, I'm not sure, but probably when something returns a None instead of a msg.

1 Like

This line will in fact exit the loop, presumably when there are no more messages:

Of course, it will do so by panicking and crashing the whole program, so the lines following the loop will still never be reached.

I assume what you want to do is replacing the .expect("Error reading message") part with proper error handling which returns from the loop? Maybe something like this:

let result = loop {
    let msg = data.read_message();
    if let Ok(msg) = msg { // or Some(msg), I didn't check the docs
        response_data.push(msg);
    } else {
        break response_data;
    }
} 

Edit: 2e71828's suggestion below is more idiomatic and readable!

1 Like

You could try something like while let Some(msg) = data.read_message() { … } instead of loop { … }

2 Likes

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.