pub trait TryNew: Sized + IntoInner {
type Error: Error;
// Required method
fn try_new(value: Self::InnerType) -> Result<Self, Self::Error>;
}Expand description
A trait for creating new instances of a type with fallible validation.
This trait provides a standardized way to create new instances of a type from an
“inner” value, where the construction process might fail (e.g., due to validation rules).
Implementors must also implement IntoInner, which defines the InnerType used
for construction.
§Associated Types
InnerType: (From theIntoInnersupertrait) The type of the input value used to attempt creation of a new instance ofSelf.Error: The error type that is returned iftry_newfails. This error type must implementstd::error::Errorif thestdfeature is enabled. If thestdfeature is not enabled, it must implementcore::fmt::Debug.
§Examples
use try_create::{TryNew, IntoInner};
// Define a custom error type
#[derive(Debug, PartialEq)]
struct NotPositiveError;
// Implement Display and Error for the custom error (required if using std::error::Error)
impl fmt::Display for NotPositiveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Value must be positive")
}
}
impl Error for NotPositiveError {}
// A struct that wraps an i32, ensuring it's positive.
#[derive(Debug, PartialEq)]
struct PositiveInteger {
value: i32,
}
// Implement IntoInner to define what `InnerType` is.
impl IntoInner for PositiveInteger {
type InnerType = i32;
fn into_inner(self) -> Self::InnerType {
self.value
}
}
// Implement TryNew for PositiveInteger.
impl TryNew for PositiveInteger {
type Error = NotPositiveError;
// `InnerType` is `i32`, inherited from `IntoInner`.
fn try_new(value: Self::InnerType) -> Result<Self, Self::Error> {
if value > 0 {
Ok(PositiveInteger { value })
} else {
Err(NotPositiveError)
}
}
}
// Usage
assert_eq!(PositiveInteger::try_new(10), Ok(PositiveInteger { value: 10 }));
assert_eq!(PositiveInteger::try_new(0), Err(NotPositiveError));
assert_eq!(PositiveInteger::try_new(-5), Err(NotPositiveError));
let positive_num = PositiveInteger::try_new(42).unwrap();
assert_eq!(positive_num.into_inner(), 42);Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".