Making something public

We saw in Chapter 7, Matching and Structures, how Rust, by default, sets all the functions, structs, and so on to be private. This is fine, as it prevents some of the nuts and bolts of the code from being exposed to the public interface.

This does mean, though, that we have to explicitly set the module, and all of the functions we want the user to have access to, to be pub (public). Therefore, our functions for the temperature conversion will be as follows:

pub mod Temperature 
{ 
    pub fn fahrenheit_to_celcius(f: f32) -> f32 
    { 
        (f - 32f32) * 5f32/9f32 
    } 

The next time we come to run the unit tests, we should not have this issue, except for the following snag:

Figure 6

We have definitely got a pub function in the Temperature module called kelvin_to_celcius. The issue is the following line:

use mathslib::conversions::temperature; 

What this does is import only the module and none of the symbols (the functions). We can fix this in one of the following four ways:

  • We can use the following:
use mathslib::conversions::temperature::*; 
  • We use the following:
use mathslib::conversions::temperature::kelvin_to_celcius; 
  • We use the following:

use mathslib::conversions::temperature; then precede kelvin_to_celcius with temperature::

  • We remove the use mathslib line and add the following line inside mod temperature_tests:
use super::*; 

Using any of these should allow the tests to compile and run. The output you will see should be something like this:

Fig 7: chap10_unittest
..................Content has been hidden....................

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