面试题答案
一键面试use std::error::Error;
// 定义自定义数据结构
#[derive(Debug)]
struct SomeComplexData {
// 自定义复杂数据结构的字段
value: String,
}
// 定义DatabaseRecord结构体
#[derive(Debug)]
struct DatabaseRecord {
id: i32,
data: SomeComplexData,
}
// 定义DatabaseError错误类型
#[derive(Debug)]
struct DatabaseError(String);
impl std::fmt::Display for DatabaseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Database error: {}", self.0)
}
}
impl Error for DatabaseError {}
// 模拟从数据库获取记录的异步函数
async fn get_database_record(id: i32) -> Result<Option<DatabaseRecord>, DatabaseError> {
// 这里通常会包含实际的数据库查询逻辑,例如使用异步数据库驱动
// 这里简单模拟返回数据
if id == 1 {
Ok(Some(DatabaseRecord {
id,
data: SomeComplexData {
value: "example data".to_string(),
},
}))
} else if id == 2 {
Ok(None)
} else {
Err(DatabaseError("模拟数据库错误".to_string()))
}
}
#[tokio::main]
async fn main() {
let record_id = 1;
match get_database_record(record_id).await {
Ok(Some(record)) => {
println!("获取到记录: {:?}", record);
}
Ok(None) => {
println!("未找到记录");
}
Err(e) => {
eprintln!("数据库错误: {}", e);
}
}
}
上述代码首先定义了自定义的数据结构SomeComplexData
和DatabaseRecord
,以及自定义错误类型DatabaseError
。get_database_record
函数模拟了从数据库获取记录的异步操作,返回Result<Option<DatabaseRecord>, DatabaseError>
。在main
函数中,使用match
语句优雅地处理了Some
、None
以及可能出现的数据库错误情况。代码使用了async/await
语法,并基于Tokio异步运行时(通过#[tokio::main]
),遵循了Rust异步编程的最佳实践。