use std::fmt;
// We have a program that loads a config and expects that
// loading the config will always succeed.
fn main() {
let _config = load_config()
.expect("config is always valid and exists");
}
// We have a dummy implementation of load_config which
// always errors, since we're just focusing on diagnostics
// here.
fn load_config() -> Result<(), Error> {
Err(Error(SourceError))
}
// And we have an error type that just prints "invalid
// config" and has a source error which just prints "config
// file does not exist"
#[derive(Debug)]
struct Error(SourceError);
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("invalid config")
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.0)
}
}
#[derive(Debug)]
struct SourceError;
impl fmt::Display for SourceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("config file does not exist")
}
}
impl std::error::Error for SourceError {}
$ cargo run
thread 'main' panicked at 'config is always valid and exists: Error(SourceError)', main.rs:4:33
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
$ cargo run
thread 'main' panicked at 'config is always valid and exists', src/main.rs:4:33
Error:
0: invalid config
1: config file does not exist
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
#[derive(Default)]
enum Option<T> {
#[default]
None,
Some(T),
}
From 日报小组 北纬27度 侯盛鑫
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。