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:
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");
}
}
}