fn readfile(filename: &str) -> Result<String, String> { let file =…
- User
fn read_file(filename: &str) -> Result<String, String> { let file = File::open(filename).map_err(|_| "找不到檔案".to_string())?; let mut reader = BufReader::new(file); let mut content = String::new(); reader.read_to_string(&mut content).map_err(|e| e.to_string())?; Ok(content) } 為何沒有io::Result
- Assistant
你的程式碼中
read_file函式的回傳型別是Result<String, String>,而非標準的io::Result<String>。這是刻意設計的結果,原因如下:
1.
io::Result是專門用來包裝 IO 錯誤的 Result:rustpub type Result<T> = std::result::Result<T, std::io::Error>;io::Result的錯誤類型是std::io::Error,它可提供完整的錯誤資訊。
2. 你的程式碼手動將錯誤轉成了字串
-
File::open(filename).map_err(|_| "找不到檔案".to_string())?;這邊將任何
File::open失敗的錯誤都轉換成了自訂的字串"找不到檔案"。 -
reader.read_to_string(&mut content).map_err(|e| e.to_string())?這裡則把錯誤轉為字串(
String)。
3. 為何不用
io::Result而用Result<_, String>?這樣做的意圖常見於:
-