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
-
Derive trait
StrongType: Create a named strong type.- The macro automatically implement common traits like
Clone,Debug,Default,PartialEq,PartialOrd,Send, andSync. It also implementsDisplayby default, unless overridden by the custom_display attribute. - Conditionally, based on the underlying data type, traits like
Copy,Eq,Ord,Hashmay also be implemented. For primitive data types likei32orbool, these additional traits will be automatically included. - Numeric types, both integer and floating-point, also implement constants
MIN,MAX, andZERO. Additionally, for floating-point types,NANis implemented.
- The macro automatically implement common traits like
-
Attributes: Adding the following attributes to
#[strong_type(...)]allows for additional features:auto_operators: Automatically implements relevant arithmetic (for numeric types) or logical (for boolean types) operators.custom_display: Allows users to manually implement theDisplaytrait, providing an alternative to the default display format.
Installation
Add strong-type to your Cargo.toml:
[]
= "0.7"
Supported underlying types:
- 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 charString
Examples
Creating a named strong type:
use StrongType;
;
let tag = new;
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 StrongType;
;
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 StrongType;
;
let x = new;
let y = new;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Custom display implementation with custom_display:
use ;
use StrongType;
;
println!; // "Second(2.72)"
println!; // "Second { value: 2.718281828459045 }"