无法从bmp::open打印错误消息

huangapple go评论59阅读模式
英文:

Cannot print error message from bmp::open

问题

我正在尝试打印出当bmp::open失败时抛出的错误

let image_result = bmp::open(argument);
let image = match image_result {
    Ok(i) => i,
    Err(error) => {
        println!("Error! {error:?}");
    },
};

但是,我一直收到以下错误消息

提前感谢!

英文:

I'm trying to print out the error it throws when bmp::open failed

let image_result = bmp::open(argument);
        let image = match image_result {
            Ok(i) => i,
            Err(error) => {
                println!("Error! {error:?}");
            },
        };

However, I've been getting the below error message

Thanks in advance!

答案1

得分: 0

由于在 Rust 中,match 语句必须从其 match 分支返回相同的类型。因此,你的第一个 match 分支

Ok(i) => i

返回了一个 Image 类型,而第二个 match 分支

Err(error) => {
     println!("Error! {error:?}");
}

没有返回任何内容,因此编译器推断返回类型为 ()(unit)类型。

有多种方法可以解决这个问题,但这实际取决于你想如何处理错误情况。如果你只想处理 Ok 的情况,你可以解构 Result

if let Ok(i) = bmp::open(argument) {
   print("Do something with {i}")
}

或者,如果文件打开失败,你可以使用 panic

let image_result = bmp::open(argument);
let image = match image_result {
    Ok(i) => i,
    Err(error) => {
        panic!("Error! {error:?}");
    }
};

或者 使用 unwrap_or_else

let img = bmp::open("test/rgbw.bmp").unwrap_or_else(|e| {
   panic!("Failed to open: {}", e);
});
英文:

This is because in Rust, the match statement has to return the same type from its match arms. So your first match arm

Ok(i) => i

returns a type of Image where as second match arm

Err(error) => {
     println!("Error! {error:?}");
}

does not return anything hence the compiler infer the return type as ()(unit) type.

There are multiple ways you could solve this, but it's really depends upon how you want to handle with the error case. If your intention is to handle only Ok case, you could destructure the Result.

if let Ok(i) = bmp::open(argument) {
   print("Do something with {i}")
}

Alternatively you can panic if the file is failed to open.

let image_result = bmp::open(argument);
let image = match image_result {
    Ok(i) => i,
    Err(error) => {
        panic!("Error! {error:?}");
    }
};

OR with unwrap_or_else,

let img = bmp::open("test/rgbw.bmp").unwrap_or_else(|e| {
   panic!("Failed to open: {}", e);
});

huangapple
  • 本文由 发表于 2023年2月18日 11:00:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定