Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error "may not be safely transferred across an unwind boundary" when using catch_unwind in Rust

I’m testing panic catch features in Rust. I have the following program:

use std::panic;

fn create_greeting(name: &str) -> String {
    //panic!("Oh no, something went wrong!");
    let greeting = format!("Hello, {}!", name);
    return greeting;
}

fn main() {
    let mut msg: String;
    let result = panic::catch_unwind(|| {
        let name = "Alice";
        msg = create_greeting(name);
    });

    match result {
        Ok(_) => {
            println!("{}", msg);
        }
        Err(_) => {
            println!("A panic occurred and was caught");
        }
    }
}

The idea is to call a function (create_greeting) that may result in panic in some circumstances (that I’m simulating uncommenting the panic! statement when I want). If everything goes fine, the program prints the result of the function, if something goes wrong it reports the user an error message.

However, I’m facing the following error when compiling the program:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

error[E0277]: the type `&mut String` may not be safely transferred across an unwind boundary
   --> src/main.rs:11:38
    |
11  |       let result = panic::catch_unwind(|| {
    |                    ------------------- ^-
    |                    |                   |
    |  __________________|___________________within this `{closure@src/main.rs:11:38: 11:40}`
    | |                  |
    | |                  required by a bound introduced by this call
12  | |         let name = "Alice";
13  | |         msg= create_greeting(name);
14  | |     });
    | |_____^ `&mut String` may not be safely transferred across an unwind boundary

How this can be solved, please?

>Solution :

Well, mutable references cannot be transferred across an unwind boundary. That’s that. What you apparently want to do is:

use std::panic;

fn create_greeting(name: &str) -> String {
    //panic!("Oh no, something went wrong!");
    format!("Hello, {name}!")
}

fn main() {
    let result = panic::catch_unwind(|| create_greeting("Alice"));

    match result {
        Ok(msg) => {
            println!("{msg}");
        }
        Err(_) => {
            println!("A panic occurred and was caught");
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading