pub trait ConditionallyCreate:
Sized
+ TryNew
+ New{
// Provided method
fn create_conditionally(value: Self::InnerType) -> Self { ... }
}Expand description
A trait for conditionally creating objects.
In debug mode, it uses Self::try_new().expect() to create an instance,
panicking if try_new returns an error.
In release mode, it uses Self::new() to create an instance.
This trait requires the type to also implement TryNew and New.
The error associated with TryNew (<Self as TryNew>::Error) must implement Debug.
§Example
use try_create::{ConditionallyCreate, TryNew, New, IntoInner};
#[derive(Debug, PartialEq)]
struct NotPositiveError;
impl fmt::Display for NotPositiveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Value must be positive")
}
}
impl Error for NotPositiveError {}
#[derive(Debug, PartialEq)]
struct PositiveInteger { value: i32 }
impl IntoInner for PositiveInteger {
type InnerType = i32;
fn into_inner(self) -> Self::InnerType { self.value }
}
impl TryNew for PositiveInteger {
type Error = NotPositiveError;
fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
if value > 0 { Ok(PositiveInteger { value }) }
else { Err(NotPositiveError) }
}
}
// To use ConditionallyCreate, PositiveInteger must also implement New.
impl New for PositiveInteger {
fn new(value: Self::InnerType) -> Self {
match Self::try_new(value) {
Ok(instance) => instance,
Err(e) => panic!("PositiveInteger::new failed for a non-positive value. Error: {:?}", e),
}
}
}
// Now you can call:
let val_ok = 10;
let _p1 = PositiveInteger::create_conditionally(val_ok);
assert_eq!(_p1, PositiveInteger { value: 10 });
// In debug, this would panic (difficult to test directly in doctest without specific harness):
// let val_err = -5;
// let _p2 = PositiveInteger::create_conditionally(val_err);Provided Methods§
Sourcefn create_conditionally(value: Self::InnerType) -> Self
fn create_conditionally(value: Self::InnerType) -> Self
Conditionally creates an instance of Self.
§Parameters
value: TheSelf::InnerTypevalue (defined byIntoInner) from which to create the instance.
§Panics
In debug mode, this method will panic if Self::try_new(value)
returns Err. The panic message will include the error’s description.
In release mode, the panic behavior depends on the implementation
of Self::new(value).
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.