英文:
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:?}");
}
};
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:?}");
}
};
let img = bmp::open("test/rgbw.bmp").unwrap_or_else(|e| {
panic!("Failed to open: {}", e);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论