| Crates.io | num-lazy |
| lib.rs | num-lazy |
| version | 0.3.0 |
| created_at | 2025-02-08 10:28:05.686925+00 |
| updated_at | 2025-09-09 15:23:12.971812+00 |
| description | Number macros for generic-typed functions. |
| homepage | https://github.com/p-sira/num-lazy |
| repository | https://github.com/p-sira/num-lazy |
| max_upload_size | |
| id | 1547927 |
| size | 17,424 |
num-lazy helps you write numbers for generic-typed functions, reduce typing, and improve readability!
Let's write a generic circumference function using num-trait.
fn circumference<T: Float>(radius: T) -> T {
T::from(2.0).unwrap() * T::from(std::f64::consts::PI).unwrap() * radius
}
This doesn't look too bad. But you can imagine it getting out of hand for more complex functions. This is where num-lazy comes to the rescue! Let's implement using num-lazy.
fn circumference<T: Float>(radius: T) -> T {
two!() * pi!() * radius
}
Install num-lazy by:
>> cargo add num-lazy
Use declare_nums!{T} to bind num-lazy to generic type T.
use num_lazy::declare_nums;
use num_traits::Float;
declare_nums!{T}
fn circumference<T: Float>(radius: T) -> T {
two!() * pi!() * radius
}
fn main() {
assert!(circumference(1.0_f64) == 6.283185307179586);
}
It is recommended to use num-lazy along with numeric-literals by using num-lazy to access macros for constants and special values, while using numeric_literals for parsing floats or numeric literals.
use num_lazy::declare_nums;
use numeric_literals::replace_numeric_literals;
use num_traits::Float;
declare_nums!{@constant T}
declare_nums!{@special T}
#[replace_numeric_literals(T::from(literal).unwrap())]
fn circumference<T: Float>(radius: T) -> T {
2 * pi!() * radius
}