paholg / dimensioned

Compile-time dimensional analysis for various unit systems using Rust's type system.
https://crates.io/crates/dimensioned
MIT License
300 stars 23 forks source link

fmt String as Joules instead of MKS #81

Closed MarkSwanson closed 2 years ago

MarkSwanson commented 2 years ago

I have a function like: fn() -> Joules. However, when I print the Joules value I get something like: 5 m^2kgs^-2 Is there an easy way to print '5 Joules' instead?

If not, what do you think a good solution to this would be? (I'm not seeing an easy way to get access to the units to compare the set of units against 'Joule' etc.) I'd be happy to take a crack at it. Thanks!

paholg commented 2 years ago

You can get the underlying value by accessing the value_unsafe field, and enforce it's an energy with a type bound as so:

fn print_joule<T: Display>(energy: Joule<T>) {
    println!("{} J", energy.value_unsafe)
}

Alternatively, you could divide by 1 Joule:

let x = Joule::new(10.0);
println!("{} J", x / Joule::new(1.0));
MarkSwanson commented 2 years ago

Got it. I like the second one as if I see anything other than Joules I know I've messed up my units. Thanks!