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?


async fn main() {
    let (mut socket, response) =
    connect(Url::parse("wss://").unwrap()).expect("Failed to connect");       
    .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();
            "type": "config",

      println!("Request sent");

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


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
    } 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 { … }