We now have the structure in place and our basic framework; we can start adding some code to the library. In this case, it will be the Conversions::Temperature part. We have already seen the function for Fahrenheit to Celcius, so let's add the other functions:
// Temperature.rs mod Temperature { fn fahrenheit_to_celcius(f: f32) -> f32 { (f - 32f32) * 5f32/9f32 } fn celcius_to_fahrenheit(f: f32) -> f32 { (c * (9f32/5f32)) + 32f32 } fn celcius_to_kelvin(c: f32) -> f32 { c + 273.15 } fn kelvin_to_celcius(k: f32) -> f32 { k - 273.15; } fn fahrenheit_to_kelvin(f: f32) -> f32 { (f + 459.67) * 5f32 / 9f32 } fn kelvin_to_fahrenheit(k: f32) -> f32 { (k * (9f32 / 5f32)) - 459.67 } }
There is nothing earth-shattering about this code, but we do have to stop for a second to think about this. The Kelvin scale goes from 0 to n; it never goes below zero. It's entirely possible for the user to want to use celcius_to_kelvin and pass -274 instead. This would mean that the answer from the function would be mathematically correct but physically incorrect.
We could return -1 but then, for some of the functions, that answer is fine.
What we need to return here is a tuple with the first parameter being a Boolean, signifying whether the calculation is valid or not (true = valid). If it's true, the answer is in the second parameter; otherwise, pass back the original value passed in.
As a quick test, the following code can be run:
fn kelvin_to_celcius(k: f32) -> (bool, f32) { if k < 0f32 { return (false, k); } else { return (true, k - 273.15); } } fn main() { let mut calc = kelvin_to_celcius(14.5); match calc.0 { true => println!("14.5K = {}C", calc.1), _ => println!("equation was invalid"), } calc = kelvin_to_celcius(-4f32); match calc.0 { true => println!("-4K = {}C", calc.1), _ => println!("invalid K"), } }
It is convenient here to use the indexed form of the tuple rather than destructuring it into two variables.
When compiled, we get the following output:
This is exactly what was expected. It does also show a need for a set of unit tests to be added into the library to determine the validity (or not) of the data being fed in.