Task 1 – cleaning the code (part 1)

If you consider the code examples in temperature.rs, you will see that some use a tuple and some use a single type return. While for development this is a fairly acceptable approach, for a release we may want something more structured.

Consider the two functions kelvin_to_celcius and celcius_to_farenheit; in order to use them, we need to have two variables:

let ktoc = kelvin_to_celcius(14.5f32); 
let ctof = celcius_to_fahrenheit(24.3f32); 

There are a number of possible solutions to this problem.

  • Do nothing! Many libraries use multiple variables when the function returns different types.
  • Implement a trait within the module that tests the return for false and returns either a String containing the answer or calculation failed.
  • Define a single struct for the answer of the form, which is then passed back to the caller, as follows:
pub struct maths_answersMathsAnswers { 
    calc_complete : bool, 
    fanswer : f32, 
    ianswer : i32, 
}  

If we remove the first option (after all, what would be the point in doing this as part of a chapter given over to testing what we have covered?), we are left with options 2 - 4 or 3.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset