Tagged

Struct Tagged 

Source
pub struct Tagged<T, Tag> { /* private fields */ }
Expand description

rust-tagged provides a simple way to define strongly typed wrappers over primitive types like String, i32, Uuid, chrono::DateTime, etc. It helps eliminate bugs caused by misusing raw primitives for conceptually distinct fields such as UserId, Email, ProductId, and more.

Eliminate accidental mixups between similar types (e.g. OrgId vs UserId) Enforce domain modeling in code via the type system Ergonomic .into() support for primitive conversions

§Example - Simple

use tagged_core::{Tagged};

#[derive(Debug)]
struct EmailTag;

type Email = Tagged<String, EmailTag>;

fn main() {
    let email: Email = "test@example.com".into();
    println!("Email inner value: {}", email.value());

    // Convert back to String
    let raw: String = email.into();
    println!("Raw String: {raw}");
}

Implementations§

Source§

impl<T, Tag> Tagged<T, Tag>

Source

pub fn new(value: T) -> Tagged<T, Tag>

Source

pub fn value(&self) -> &T

Source§

impl<T, Tag> Tagged<T, Tag>

§Example - Mutation

use tagged_core::Tagged;

#[derive(Debug)]
struct Org;

type OrgName = Tagged<String, Org>;

fn main() {
    let mut name = OrgName::new("Codefonsi".into());

    name.set("New Org Name".into());

    println!("Updated Org Name: {}", name.value());
}
Source

pub fn set(&mut self, new_value: T)

Not allowed feature - Get a mutable reference to the internal value Replace the inner value

Trait Implementations§

Source§

impl<T, Tag> Clone for Tagged<T, Tag>
where T: Clone,

Source§

fn clone(&self) -> Tagged<T, Tag>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T, Tag> Debug for Tagged<T, Tag>
where T: Debug,

§Example - Debug

use tagged_core::Tagged;


#[derive(Debug)]
struct UserIdTag {
    a: Tagged<u32, Self>,
    b: Tagged<u32, Self>,
}


fn main() {
    let instance = UserIdTag{a: 1.into(), b: 2.into()};

    println!("{}", instance.a);
    println!("{:?}", instance.b);
}
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<T, Tag> Deref for Tagged<T, Tag>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<Tagged<T, Tag> as Deref>::Target

Dereferences the value.
Source§

impl<'de, T, Tag> Deserialize<'de> for Tagged<T, Tag>
where T: Deserialize<'de>,

Available on crate feature serde only.
use serde::{Deserialize, Serialize};
use tagged_core::Tagged;
 
#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct SomeCustomType {
    some_id: String
}
#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct SomeCustomType2(String);
#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    id: Tagged<String, Self>,
    id2: SomeCustomType,
    id3: SomeCustomType2,
}
 
 
fn main() {
    let user = User { id: "1".into() , id2: SomeCustomType { some_id: "2".into() }, id3: SomeCustomType2("3".into())};
    let j = serde_json::to_string(&user).unwrap();
    let converted_user = serde_json::from_str::<User>(&j).unwrap();
    println!("{}", j);
    println!("{:?}", converted_user);
}
/*
 Running `target/debug/examples/Serde_example`
{"id":"1","id2":{"some_id":"2"},"id3":"3"}
User { id: "1", id2: SomeCustomType { some_id: "2" }, id3: SomeCustomType2("3") }
 
Process finished with exit code 0
*/
 
/*
Problem with normal types
{"id":"1","id2":{"some_id":"2"}}
 
// rust is powerful enough to solve it using touple 
{"id":"1","id2":{"some_id":"2"},"id3":"3"}
 
// or we can use a new type called tagged that don't need a new name.
*/
Source§

fn deserialize<D>( deserializer: D, ) -> Result<Tagged<T, Tag>, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T, Tag> Display for Tagged<T, Tag>
where T: Display,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl<Tag> From<&String> for Tagged<String, Tag>

Support From<&String>Tagged<String, Tag>

Source§

fn from(s: &String) -> Tagged<String, Tag>

Converts to this type from the input type.
Source§

impl<Tag> From<&str> for Tagged<String, Tag>

Support From<&str>Tagged<String, Tag>

Source§

fn from(s: &str) -> Tagged<String, Tag>

Converts to this type from the input type.
Source§

impl<T, Tag> From<T> for Tagged<T, Tag>

Blanket From<T> for Tagged<T, Tag>

Source§

fn from(value: T) -> Tagged<T, Tag>

Converts to this type from the input type.
Source§

impl<T, Tag> Hash for Tagged<T, Tag>
where T: Hash,

§Example - Hash

fn main() {
    use tagged_core::Tagged;
    use std::collections::HashSet;

    #[derive(Clone, Hash, Debug, PartialEq, Eq)]
    struct User {
        id: Tagged<String, Self>
    }
    let mut s: HashSet<User> = HashSet::new();
    let user = User{id: "me@example.com".into()};
    s.insert(user.clone());

    assert!(s.contains(&user));
}
Source§

fn hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<'a, T, Tag> IntoIterator for &'a Tagged<Vec<T>, Tag>

use tagged_core::Tagged;
 
#[derive(Debug)]
struct Org;
 
type EmployeeNames = Tagged<Vec<String>, Org>;
 
fn main() {
    let names: EmployeeNames = Tagged::new(vec!["Alice".into(), "Bob".into()]);
    names.iter().for_each(|name| println!("Name: {}", name));
}
 
/*
Name: Alice
Name: Bob
*/
Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <&'a Tagged<Vec<T>, Tag> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T, Tag> IntoIterator for Tagged<Vec<T>, Tag>

use tagged_core::Tagged;
 
#[derive(Debug)]
struct Org;
 
type EmployeeNames = Tagged<Vec<String>, Org>;
 
fn main() {
    let names: EmployeeNames = Tagged::new(vec!["Alice".into(), "Bob".into()]);
    names.into_iter().for_each(|name| println!("Name: {}", name));
}
 
/*
Name: Alice
Name: Bob
*/
Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> <Tagged<Vec<T>, Tag> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T, Tag> Ord for Tagged<T, Tag>
where T: Ord,

Source§

fn cmp(&self, other: &Tagged<T, Tag>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T, Tag> PartialEq for Tagged<T, Tag>
where T: PartialEq,

Source§

fn eq(&self, other: &Tagged<T, Tag>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T, Tag> PartialOrd for Tagged<T, Tag>
where T: PartialOrd,

Source§

fn partial_cmp(&self, other: &Tagged<T, Tag>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T, Tag> Serialize for Tagged<T, Tag>
where T: Serialize,

Available on crate feature serde only.

Example - Serialize

use serde::{Deserialize, Serialize};
use tagged_core::Tagged;

#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct SomeCustomType {
    some_id: String
}
#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct SomeCustomType2(String);
#[derive(Clone, Hash, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    id: Tagged<String, Self>,
    id2: SomeCustomType,
    id3: SomeCustomType2,
}


fn main() {
    let user = User { id: "1".into() , id2: SomeCustomType { some_id: "2".into() }, id3: SomeCustomType2("3".into())};
    let j = serde_json::to_string(&user).unwrap();
    println!("{}", j);
}

/*
Problem with normal types
{"id":"1","id2":{"some_id":"2"}}

// rust is powerful enough to solve it using touple
{"id":"1","id2":{"some_id":"2"},"id3":"3"}

// or we can use a new type called tagged that don't need a new name.
*/
Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T, Tag> Taggable for Tagged<T, Tag>

Source§

fn type_name(&self) -> &'static str

Get the inner value type name for debugging
Source§

impl<T, Tag> Eq for Tagged<T, Tag>
where T: Eq,

Auto Trait Implementations§

§

impl<T, Tag> Freeze for Tagged<T, Tag>
where T: Freeze,

§

impl<T, Tag> RefUnwindSafe for Tagged<T, Tag>

§

impl<T, Tag> Send for Tagged<T, Tag>
where T: Send, Tag: Send,

§

impl<T, Tag> Sync for Tagged<T, Tag>
where T: Sync, Tag: Sync,

§

impl<T, Tag> Unpin for Tagged<T, Tag>
where T: Unpin, Tag: Unpin,

§

impl<T, Tag> UnwindSafe for Tagged<T, Tag>
where T: UnwindSafe, Tag: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,