我有一个用户的域模型,其中存储了original
个用户状态和current
个用户状态.如果当前状态的属性不匹配原始—它需要在数据库中更新并包含在SQL查询中.
for each 属性创建类似的比较方法变得重复,我想知道,有没有一种方法可以用一些通用的共享方法来替换这个比较方法?
注意:如果实现起来更简单,可以将原始的更改为非可选的.它用于区分刚创建的模型的插入和更新SQL操作
#[derive(Debug, Clone)]
struct UserProps {
pub age: i32,
pub name: String,
}
struct User {
pub original: Option<UserProps>,
pub current: UserProps,
}
impl User {
// creating similar function for each property is burthersome
// is there a way to create a generic one?
pub fn age_changed(&self) -> bool {
self.original
.as_ref()
.map_or(true, |val| val.age != self.current.age)
}
pub fn name_changed(&self) -> bool {
self.original
.as_ref()
.map_or(true, |val| val.name != self.current.name)
}
}
fn x() {
let props = UserProps {
age: 12,
name: "x".to_owned(),
};
let mut user = User {
original: Some(props.clone()),
current: props.clone(),
};
user.current.age = 22;
assert!(user.age_changed());
if user.age_changed() {
// add property to sql query update operation
}
}
在JavaScript中,我会这样做:
propertyChanged(propName: string): boolean {
if (this.original === undefined){
return true
}
return this.original[propName] !== this.current[propName]
}