简体   繁体   English

Rust - 如何返回不同 function 的错误?

[英]Rust - how can I return error of a different function?

Given two functions like these:给定两个这样的函数:

fn foo() -> Result<i32, Box<dyn std::error::Error>> {
    // returns an error if something goes wrong
}

fn bar() -> Result<bool, Box<dyn std::error::Error>> {
   let x = foo(); // could be ok or err
   if x.is_err() {
       return // I want to return whatever error occured in function foo
    }
}

Is it possible to return the exact error that appeared in function foo from function bar ?是否可以从 function bar返回 function foo中出现的确切错误? Also notice, the Result<T, E> enum has different T in these functions另请注意, Result<T, E>枚举在这些函数中具有不同的T

I would just let the ?我会让? operator do all the work. 操作员完成所有工作。

fn foo(a: i32) -> Result<i32, Box<dyn std::error::Error>> {
    if a < 10 {
        // returns an error if something goes wrong
        Err(Box::from("bad value"))
    } else {
        Ok(a + 2)
    }
}

fn bar(a: i32) -> Result<bool, Box<dyn std::error::Error>> {
    let x = foo(a)?;
    Ok(x > 5)
}

fn main() {
    println!("{:?}", bar(2)); //  displays Err("bad value")
    println!("{:?}", bar(12)); // displays Ok(true)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Rust 中的成员 function 返回泛型类型 - How can I return a generic type from a member function in Rust 如何在 Rust 中返回 gpio_cdev::Error? - How can I return a gpio_cdev::Error in Rust? 如何解决 Rust 中的此返回类型 function 错误 - How to solve this return type function error in Rust Rust - 如何从函数返回多个变量,以便在调用函数的范围之外可以访问它们? - Rust - How can I return multiple variables from a function such that they are accessible outside the scope the function is called in? 我如何打电话给Z72812E30873455DCEE2D1E2D1EE26E4ABZ ZC1C425268E6838385D1AB5074C174C174C174C174F14Z in Z72812E3087345555DCEE2CE2CE2D1EE2D1EE2D1EE26E26E4ABZ INLINE ASM MODLINE ASM MODLINE ASM MODLINE ASM MODLINE - How can I call a rust function in rust inline asm module A Rust function 返回一个future,after.await(),可能会引发恐慌。? 我怎样才能避免恐慌! 停止程序? - A Rust function return a future, after .await(), it may be throw a panic!. How can I avoid the panic! to stop the program? Rust SDL2 定时器:如何从 function 返回定时器 object? - Rust SDL2 Timer: How can I return timer object from the function? 如何编写Rust函数以查找两个字符串之间的不同字符? - How can I write a Rust function to find different characters between two strings? 如何在 Rust 函数中返回一个数组 - How to return an array in Rust function 如何修复无法返回值引用 Rust 中的 function 参数错误 - How to fix cannot return value referencing function parameter error in Rust
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM