pub trait TryNull: Sized {
type Error;
// Required methods
fn try_null() -> Result<Self, Self::Error>;
fn is_null(&self) -> bool;
}Expand description
Fallible version of Null for types where null value creation can fail.
This trait is useful when:
- Null value creation requires allocation
- Validation is needed during null value construction
- Construction can fail in constrained environments
- External resources are needed to create the null value
§Relationship to Null
While Null provides infallible null value creation, TryNull handles
cases where construction might fail. If your type’s null value is always
constructible, prefer implementing Null instead.
§Thread Safety
This trait is Send + Sync safe when implemented on thread-safe types
with thread-safe error types.
§Examples
use multi_trait::TryNull;
#[derive(Debug)]
struct BufferId(Vec<u8>);
impl TryNull for BufferId {
type Error = std::collections::TryReserveError;
fn try_null() -> Result<Self, Self::Error> {
let mut vec = Vec::new();
vec.try_reserve(1)?;
vec.push(0);
Ok(BufferId(vec))
}
fn is_null(&self) -> bool {
self.0.len() == 1 && self.0[0] == 0
}
}
match BufferId::try_null() {
Ok(null_buf) => assert!(null_buf.is_null()),
Err(e) => eprintln!("Failed to create null buffer: {}", e),
}§Implementation Guidelines
- The error type should describe why null creation failed
- If
try_null()succeeds, the result should satisfyis_null() - The null value should be consistent across successful calls
Required Associated Types§
Required Methods§
Sourcefn try_null() -> Result<Self, Self::Error>
fn try_null() -> Result<Self, Self::Error>
Try to construct a null/sentinel value of this type.
Returns Ok with a null value if successful, or Err if null value
creation failed (e.g., due to allocation failure or validation error).
§Errors
Returns an error if null value construction fails. The exact error conditions are type-specific.
§Examples
use multi_trait::TryNull;
let null_id = ValidatedId::try_null()?;
assert!(null_id.is_null());Sourcefn is_null(&self) -> bool
fn is_null(&self) -> bool
Check if this value is the null value.
Returns true if this instance represents the null/sentinel value,
false otherwise. This method is identical to Null::is_null.
§Examples
use multi_trait::TryNull;
let data = OptionalData::try_null().unwrap();
assert!(data.is_null());Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".