The struct option

The problem with the third option is that, when we call within the library, we either have a return type of tuple(bool, f32) or f32. Therefore, in a function that only returns a single type, we will need to set calc_completed to true.

It is possible to set a default value on the struct by deriving or implementing std::Default (we will cover the standard library in Chapter 13, The Standard Library,  and Chapter 14Foreign Function Interfaces). Here's a derived version:

#[derive(Default)] 
pub struct MathsAnswers { 
    calc_complete : bool, 
    fanswer : f32, 
    ianswer : i32, 
}  

All primitive types in Rust have a sensible default value: numbers are zeroes, bool is false, Strings are empty strings, and so on. The preceding code is equivalent to the following manually implemented Default :

impl Default for MathsAnswers { 
  fn default () -> MathsAnswers { 
    MathsAnswers {calc_complete: false, fanswer: 0f32, ianswer: 0i32 } 
  } 
} 

However, we want the calc_complete default to be true, so we'll use this implementation instead:

impl Default for MathsAnswers { 
  fn default () -> MathsAnswers { 
    MathsAnswers {calc_complete: false, fanswer: 0f32, ianswer: 0i32 } 
  } 
} 

After the Default implementation, we may choose to only fill in some of the values when creating an instance and supply Default::default() for the rest:

// do calculation then
let answers = MathsAnswers { fanswer: calc_ans, ..Default::default() }; return MathsAnswers;

The potential problem is where to put the struct in terms of scope. Where would it be best to place it?

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

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