Rust.cc

Rust.cc -

使用?操作符无法格式化错误消息

示例代码: use std::fmt; #[derive(Debug)] struct AppError { kind: String, message: String, } impl std::error::Error for AppError {} impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match &self.kind as &str { "404" => write!( f, "程序出错:{{错误类型: {}, 错误原因: {}}}", self.kind, self.message ), _ => write!(f, "Sorry, something is wrong! Please Try Again!"), } } } fn produce_error() -> Result<(), AppError> { Err(AppError { kind: String::from("404"), message: String::from("Page not found"), }) } fn main() -> Result<(), Box<dyn std::error::Error>> { match produce_error() { Err(err) => println!("{}", err), _ => println!("No error"), } Ok(()) } 运行后正常调用fmt方法格式化输出: 程序出错:{错误类型: 404, 错误原因: Page not found} 使用?操作符,将main函数修改为: fn main() -> Result<(), Box<dyn std::error::Error>> { produce_error()?; Ok(()) } 再次运行后输出: Error: AppError { kind: "404", message: "Page not found" } 无法调用fmt方法格式化输出! playground 求解

相关推荐 去reddit讨论

热榜 Top10

观测云
观测云
Dify.AI
Dify.AI
eolink
eolink
LigaAI
LigaAI

推荐或自荐