Skip to main content

Wrapped

Trait Wrapped 

Source
pub trait Wrapped:
    ValueObject
    + WrappedInner
    + TryFrom<Self::Inner>
where Self::Error: Error + Send + Sync + 'static,
{ // Required methods fn as_inner(&self) -> &Self::Inner; fn into_inner(self) -> Self::Inner; }
Expand description

A ValueObject newtype around a single WrappedInner::Inner value, only constructible through validation (TryFrom<Self::Inner>).

Note this invariant only holds if the wrapped field is private - see #[derive(ValueObject)] in ddd-toolkit-macro, which enforces that at derive time.

§Examples

use ddd_toolkit_core::domain::{ValidationError, ValueObject, Wrapped, WrappedInner};

#[derive(Debug, Clone, PartialEq)]
struct NonEmptyString(String);

impl ValueObject for NonEmptyString {}

impl WrappedInner for NonEmptyString {
    type Inner = String;
}

impl Wrapped for NonEmptyString {
    fn as_inner(&self) -> &Self::Inner {
        &self.0
    }

    fn into_inner(self) -> Self::Inner {
        self.0
    }
}

impl TryFrom<String> for NonEmptyString {
    type Error = ValidationError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        if value.trim().is_empty() {
            return Err(ValidationError::new("NonEmptyString", "empty"));
        }
        Ok(Self(value))
    }
}

let name: NonEmptyString = "alice".to_string().try_into()?;
assert_eq!(name.as_inner(), "alice");
assert_eq!(name.into_inner(), "alice".to_string());

assert!(NonEmptyString::try_from(String::new()).is_err());

Required Methods§

Source

fn as_inner(&self) -> &Self::Inner

Borrows the wrapped value.

Source

fn into_inner(self) -> Self::Inner

Consumes self, returning the wrapped value.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§