Rust 是选项<;i32>;放松安全吗?
我正在实现一个C库的包装器,它接受回调,回调将在Rust中实现。鉴于此,我想在他们进入C之前抓住任何潜在的锈菌恐慌 我一直在读有关std::panic::catch\u unwind的文章。包装器对性能非常敏感,我希望避免使用Rust 是选项<;i32>;放松安全吗?,rust,ffi,Rust,Ffi,我正在实现一个C库的包装器,它接受回调,回调将在Rust中实现。鉴于此,我想在他们进入C之前抓住任何潜在的锈菌恐慌 我一直在读有关std::panic::catch\u unwind的文章。包装器对性能非常敏感,我希望避免使用Mutex之类的类型。我想将结果保存在选项中并将其设置为Some(value),以防出现恐慌无将指示函数未成功执行,因此一定发生了死机 选项放卷安全吗?如果没有,在什么情况下会出现问题?我可以用std::panic::AssertUnwindSafe包装它吗 下面是一个示例
Mutex
之类的类型。我想将结果保存在选项中
并将其设置为Some(value)
,以防出现恐慌<代码>无将指示函数未成功执行,因此一定发生了死机
选项
放卷安全吗?如果没有,在什么情况下会出现问题?我可以用std::panic::AssertUnwindSafe
包装它吗
下面是一个示例,我使用AssertUnwindSafe
来包装整个闭包
use std::panic::{self, AssertUnwindSafe};
fn random_function_that_might_panic(a: i32) -> i32 {
if a == 42 {
panic!("did you forget a towel?");
}
a * 2
}
fn do_not_panic(a: i32) {
let mut result = None;
let unwind_state = panic::catch_unwind(AssertUnwindSafe(|| {
result = Some(random_function_that_might_panic(a)); // get result, but this could panic
}));
match unwind_state {
Ok(()) => {
match result {
Some(value) => {
println!("Result: {:?}", value);
}
None => {
// this should never happen...
println!("No result but no panic?");
}
}
}
Err(e) => {
println!("caught panic: {:?}", e);
}
}
}
fn main() {
do_not_panic(1);
do_not_panic(2);
do_not_panic(3);
do_not_panic(42);
}
(请参见上的。)
我不知道如何在AssertUnwindSafe
中只包装选项
,所以在这里我包装了整个闭包。如何仅包装选项
选项
放卷安全吗
对。当你可以问编译器时,没有理由问人类这个问题:
fn implements<T: std::panic::UnwindSafe>() {}
fn main() {
implements::<Option<i32>>();
}
我会这样写你的代码,不管它值多少钱:
fn do_not_panic(a: i32) {
let result = panic::catch_unwind(|| random_function_that_might_panic(a)).ok();
match result {
Some(value) => {
println!("Result: {:?}", value);
}
None => {
println!("caught panic");
}
}
}
没有可变变量,没有额外的嵌套,没有“这永远不会发生”的注释
另见:
选项
放卷安全吗
对。当你可以问编译器时,没有理由问人类这个问题:
fn implements<T: std::panic::UnwindSafe>() {}
fn main() {
implements::<Option<i32>>();
}
我会这样写你的代码,不管它值多少钱:
fn do_not_panic(a: i32) {
let result = panic::catch_unwind(|| random_function_that_might_panic(a)).ok();
match result {
Some(value) => {
println!("Result: {:?}", value);
}
None => {
println!("caught panic");
}
}
}
没有可变变量,没有额外的嵌套,没有“这永远不会发生”的注释
另见:
catch_unwind()
在成功后返回结束的结果。)你似乎在一旁(“我会这样写你的代码,不管它值多少钱”),实际上实现了我想要的,谢谢你。(我不确定我怎么会错过了catch_unwind()
成功返回关闭结果。)