Add ActiveValue::try_as_ref() (#2197)

This commit is contained in:
Dmitrii Aleksandrov 2024-05-09 20:44:37 +04:00 committed by GitHub
parent aa626fc1fd
commit e162a1be9e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -849,6 +849,26 @@ where
None => ActiveValue::NotSet, None => ActiveValue::NotSet,
}; };
} }
/// Get the inner value, unless `self` is [NotSet][ActiveValue::NotSet].
///
/// There's also a panicking version: [ActiveValue::as_ref].
///
/// ## Examples
///
/// ```
/// # use sea_orm::ActiveValue;
/// #
/// assert_eq!(ActiveValue::Unchanged(42).try_as_ref(), Some(&42));
/// assert_eq!(ActiveValue::Set(42).try_as_ref(), Some(&42));
/// assert_eq!(ActiveValue::NotSet.try_as_ref(), None::<&i32>);
/// ```
pub fn try_as_ref(&self) -> Option<&V> {
match self {
ActiveValue::Set(value) | ActiveValue::Unchanged(value) => Some(value),
ActiveValue::NotSet => None,
}
}
} }
impl<V> std::convert::AsRef<V> for ActiveValue<V> impl<V> std::convert::AsRef<V> for ActiveValue<V>
@ -857,7 +877,9 @@ where
{ {
/// # Panics /// # Panics
/// ///
/// Panics if it is [ActiveValue::NotSet] /// Panics if it is [ActiveValue::NotSet].
///
/// See [ActiveValue::try_as_ref] for a fallible non-panicking version.
fn as_ref(&self) -> &V { fn as_ref(&self) -> &V {
match self { match self {
ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value, ActiveValue::Set(value) | ActiveValue::Unchanged(value) => value,