在 Rust 中使用 catch_unwind 时出现错误“可能无法安全地跨展开边界传输”

问题描述 投票:0回答:1

我正在测试 Rust 中的恐慌捕获功能。我有以下程序:

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

这个想法是调用一个函数(

create_greeting
),在某些情况下可能会导致恐慌(我正在模拟在需要时取消注释
panic!
语句)。如果一切顺利,程序会打印函数的结果,如果出现问题,则会向用户报告错误消息。

但是,我在编译程序时遇到以下错误:

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

请问这个问题如何解决?

rust
1个回答
0
投票

嗯,可变引用不能跨展开边界传输。就是这样。您显然想做的是:

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(|| {
        let name = "Alice";
        create_greeting(name)
    });

    match result {
        Ok(msg) => {
            println!("{}", msg);
        }
        Err(_) => {
            println!("A panic occurred and was caught");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.