我是 Rust 的新手,我编写了一个函数,该函数返回带有 Box dyn 错误的结果。
use std::error::Error;
fn func<T>(val: T) -> Result<(), Box<dyn Error>>
where
T: std::fmt::Debug,
{
println!("{:?}", val);
Ok(())
}
fn main() {
func("hello world");
}
这里我没有在函数 func
中编写任何错误逻辑,但它仍然有效。上面的代码会自动捕获所有错误吗?类似于python的
try:
# Run the code
except:
# Catch all the errors
在 Rust 中是否有任何通用的错误捕获方式?
答案 0 :(得分:5)
如果您对此运行 warning: unused `std::result::Result` that must be used
--> src/main.rs:12:5
|
12 | func("hello world");
| ^^^^^^^^^^^^^^^^^^^^
|
,您将收到以下警告:
func
这告诉您,虽然 Result
返回一个可能是错误的 fn main() -> Result<(), Box<dyn Error>> {
func("hello world")?; // If this fails, the `?` makes main return it
Ok(())
}
,但您并没有对它做任何事情。
您需要处理错误 - 最简单的方法是更改 main 以返回错误:
func
现在 main
失败了,anyhow
也会失败。
要看到它的实际效果,我们需要一个错误类型 - 实现起来有点乏味(例如,请参阅 here 了解详细信息)。相反,我将转换为使用 use anyhow::{anyhow, Result};
fn func<T>(val: T) -> Result<()>
where
T: std::fmt::Debug,
{
println!("{:?}", val);
Err(anyhow!("BANG"))
}
fn main() -> Result<()> {
func("hello world")?;
Ok(())
}
来处理错误。
func
现在 "hello world"
Error: BANG
返回错误,并运行二进制输出:
func
如果您不希望应用程序在出错时退出,或者不希望它以这种方式退出,那么您需要自己处理来自 use anyhow::{anyhow, Result};
fn func<T>(val: T) -> Result<()>
where
T: std::fmt::Debug,
{
println!("{:?}", val);
Err(anyhow!("BANG"))
}
fn main() {
match func("hello world") {
Err(e) => println!("an error: {:?}", e), //<= error handling
Ok(_) => println!("func was OK"),
}
}
的结果
"hello world"
an error: BANG
将输出:
TreeMap<Float, String> map = new TreeMap<>(Collections.reverseOrder());
for (String user : input.split(", ")) {
String[] split = user.split(";q=");
map.put(split.length == 1 ? (map.lastKey() - 1f) : Float.valueOf(split[1]), split[0]);
}
return map.values();