在 Rust 中,可以使用 Result
類型和 ?
運算符來處理多種錯誤類型。Result
是一個枚舉類型,表示操作可能成功(Ok
)或失?。?code>Err)。你可以使用 ?
運算符將錯誤從函數中傳播出去,以便在調用棧中更高層的地方處理它們。
以下是一個示例,展示了如何處理兩種不同的錯誤類型:
use std::fs::File;
use std::io::{self, Read};
#[derive(Debug)]
enum CustomError {
IOError(io::Error),
ParseError(std::num::ParseIntError),
}
impl From<io::Error> for CustomError {
fn from(error: io::Error) -> Self {
CustomError::IOError(error)
}
}
impl From<std::num::ParseIntError> for CustomError {
fn from(error: std::num::ParseIntError) -> Self {
CustomError::ParseError(error)
}
}
fn read_file_contents(file_name: &str) -> Result<String, CustomError> {
let mut file = File::open(file_name)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn main() {
match read_file_contents("example.txt") {
Ok(contents) => println!("File contents: {}", contents),
Err(e) => match e {
CustomError::IOError(io_error) => println!("IO error: {:?}", io_error),
CustomError::ParseError(parse_error) => println!("Parse error: {:?}", parse_error),
},
}
}
在這個示例中,我們定義了一個名為 CustomError
的枚舉類型,用于表示兩種不同的錯誤類型:IOError
和 ParseError
。我們還實現了 From
trait,以便可以將 io::Error
和 std::num::ParseIntError
轉換為 CustomError
。
read_file_contents
函數嘗試打開一個文件并將其內容讀取到字符串中。如果發生任何錯誤,它將使用 ?
運算符將錯誤傳播出去,并在 main
函數中處理它們。在 main
函數中,我們使用 match
語句來處理 read_file_contents
返回的 Result
類型。如果操作成功,我們將打印文件內容;如果失敗,我們將根據錯誤類型打印相應的錯誤消息。