面试题答案
一键面试use std::fmt;
// 自定义错误类型
#[derive(Debug)]
struct EmailFormatError;
impl fmt::Display for EmailFormatError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Email格式不正确")
}
}
// 定义User结构体
struct User {
email: String,
}
impl User {
// 设置email的方法
fn set_email(&mut self, new_email: &str) -> Result<(), EmailFormatError> {
if is_valid_email(new_email) {
self.email = new_email.to_string();
Ok(())
} else {
Err(EmailFormatError)
}
}
}
// 简单的邮箱格式验证函数
fn is_valid_email(email: &str) -> bool {
email.contains('@') && email.contains('.')
}
在上述代码中:
- 定义了一个自定义错误类型
EmailFormatError
,实现了Debug
和Display
特征。 - 定义了
User
结构体,包含email
字段。 - 在
User
结构体上实现了set_email
方法,该方法接收一个字符串切片,验证邮箱格式后设置email
字段,若格式不正确返回错误。 - 提供了一个简单的
is_valid_email
函数用于验证邮箱格式(实际应用中可以使用更完善的正则表达式等方式验证)。