面试题答案
一键面试use std::fs::File;
use std::io::{self, Read};
struct FileProcessor {
// 可以在这里添加结构体需要的字段,如果有的话
}
impl FileProcessor {
fn open_file(&self, filename: &str) -> Result<File, io::Error> {
File::open(filename)
}
fn read_content(&self, file: File) -> Result<String, io::Error> {
let mut content = String::new();
file.read_to_string(&mut content)?;
Ok(content)
}
fn process_content(&self, content: String) -> Result<String, &'static str> {
// 这里进行内容处理,简单示例:如果内容为空则返回错误
if content.is_empty() {
Err("Content is empty")
} else {
Ok(content.to_uppercase())
}
}
fn chain_operations(&self, filename: &str) -> Result<String, Box<dyn std::error::Error>> {
self.open_file(filename)?
.and_then(|file| self.read_content(file))?
.and_then(|content| self.process_content(content))
}
}
你可以使用以下方式测试这个链式调用:
fn main() {
let processor = FileProcessor;
match processor.chain_operations("test.txt") {
Ok(result) => println!("Processed content: {}", result),
Err(e) => println!("Error: {}", e),
}
}
代码说明:
FileProcessor
结构体:定义了一个FileProcessor
结构体,目前没有实际字段,因为示例代码中未用到特定字段。open_file
方法:尝试打开指定文件名的文件,返回Result<File, io::Error>
,io::Error
是标准库中文件操作可能产生的错误类型。read_content
方法:接受一个打开的File
,将文件内容读取到String
中并返回Result<String, io::Error>
。process_content
方法:接受读取的文件内容String
,对其进行处理。这里简单示例为如果内容为空返回错误,否则将内容转为大写并返回Result<String, &'static str>
。chain_operations
方法:通过链式调用open_file
、read_content
和process_content
方法,使用?
操作符处理每个步骤可能产生的错误,并将错误传递。如果任何一步出错,整个链式调用将提前终止并返回错误。main
函数:创建FileProcessor
实例并调用chain_operations
方法,根据返回的Result
打印处理结果或错误信息。