Let's say I have function that accept arguments to update a user like this:
pub struct User {
pub user_id: Uuid,
pub nickname: String,
pub avatar: Option<String>,
}
pub struct UserUpdateProps {
pub user_id: Uuid,
pub nickname: Option<String>,
pub avatar: Option<String>,
}
There is many props and operations like this. Update props are passed around, so you can't go with path call
or not call
an instance.
For nickname
Option<String>
works fine, it means if no nickname passed - no change required.
For avatar
Option<String>
doesn't work, because we can't handle two cases - unset and do nothing.
In javascript undefined
would mean do nothing, null
unset value.
What is the idiomatic way to handle this in rust?
Based on @Chayim Friedman suggestion, general usage enum seems the best way.
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
pub enum ValueOrNull<T> {
Undefined,
Null,
Value(T),
}
impl<T> Default for ValueOrNull<T> {
fn default() -> Self {
Self::Undefined
}
}