strong-type
strong-type is a Rust crate that offers macros to easily create strongly typed and named primitive and string types. Strong typing helps in making code more expressive and less prone to errors, ensuring that each type is used in its intended way.
use StrongType;
;
let timestamp = new;
println!; // Timestamp(1701620628123456789)
Features
StrongType: Create a named strong type. The macro automatically implement common traits likeClone,Debug,Default,PartialEq,PartialOrd,Send,Sync, andDisplay(unless thecustom_displayattribute is used to override it). Additionally, depending on the underlying data type, strong-typed structs may also implementCopy,Eq,Ord,Hash. For example, if the underlying type is a primitive data type likei32orbool, these additional traits will be implemented. This allows the strong types to inherit useful behaviors from their underlying types, while still maintaining their distinct identity at the type level.StrongNumericType: ExtendStrongTypewith arithmetic/logical operations.custom_display: Provides flexibility for users to manually implementDisplayinstead of using the default display format.
Installation
Add strong-type to your Cargo.toml:
[]
= "*" # Using the latest version or specify a version number
Supported underlying types:
- Both
StrongTypeandStrongNumericType:- Integer types:
i8,i16,i32,i64,i128,isize - Unsigned integer types:
u8,u16,u32,u64,u128,usize - Floating-point types:
f32,f64 - Boolean type:
bool
- Integer types:
- Only
StrongType:charString
Examples
Creating a named strong type:
use StrongType;
;
let tag = new;
let tag: Tag = "dev".into; // Alternative instantiation
Demonstrating type distinctiveness:
use StrongType;
use Any;
;
;
let x = new;
let y = new;
let z = new;
assert_eq!; // Same type: Second
assert_ne!; // Different types: Second versus Minute
Utilizing Hashability:
use HashSet;
;
let mut map = new;
map.insert;
map.insert;
assert_eq!;
Named integer type with arithmetic operations:
use StrongNumericType;
;
let x = new;
let y = new;
let z = default;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
assert!;
assert_eq!;
Named bool type with logical operations:
use StrongNumericType;
;
let x = new;
let y = new;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Custom display implementation with custom_display:
use ;
use StrongNumericType;
;
println!; // "Second(2.72)"
println!; // "Second { value: 2.718281828459045 }"