Software Development:- Function Declaration – Exceptions – Rust – Using

Background

In the course of software application development, a good engineer will have a read of errors that can be encoutered when the application is ran.

Lineage

  1. Software Development:- Function Declaration – Exceptions – Java
    Link
  2. Software Development:- Function Declaration – Exceptions – Rust
    Link

Code

Outline

  1. Import
    • std::error::Error
  2. Constants
    • const emptyString:&str = “”;
    • const isKJV_false:bool = false;
  3. Declare Variables
    • structures
      • Congregant
        • personName:String
        • bibleTranslation:String
        • isKJV:bool
        • err:String
  4. Functions
    • listView
      • Arguments
        • list_of_Congregant:Vec<Congregant>
      • Steps
        • Iterate List
          • for (i, x) in list_of_Congregant.iter().enumerate()
    • listEvaluate
      • Arguments
        • list_of_Congregant:&mut Vec<Congregant>
      • Steps
        • Iterate List
          • for x in list_of_Congregant.iter_mut()
            • As list will be modified replaced iter with iter_mut
          • reset contextual variables
            • errLocal
              • errLocal = “”.to_string();
          • Make copy of contextual data
            • bibleTranslation
              • bibleTranslationLocal = x.bibleTranlation.to_owned();
          • Invoke Function ( bibleIsKJV )
            • isKJV_context = bibleIsKJV(bibleTranslationLocal);
          • Review Function Return Value ( isKJV_context )
            • is_ok()
              • If isKJV_context.is_OK
                • Unwrap Result
                  • isKJV = isKJV_context.unwrap();
            • is_err()
              • If isKJV_context.is_err()
                • Unwrap Error
                  • let err = isKJV_context.unwrap_err();
                • save errorLocal
                  • errLocal = err.to_string()
    • bibleIsKJV
      • Function Declaration
        • fn bibleIsKJV ( bibleTranslation:String ) -> Result<bool, Box<dyn Error>>
      •  Arguments
        • bibleTranslation:String
      • Return
        • Result<bool, Box<dyn Error>>
      • Steps
        • if bibleTranslation != “KJV”
          • Format Error Message
            •  errorMessage = format! ( "Bible is not KJV. It is '{0}'" , bibleTranslation ); 
          • Raise Exception
            •  return Err ( errorMessage.into() ); 
  5. Main Function
    • Declare Variables
      • declare list
        • let mut list_of_Congregant: Vec<Congregant>;
      • declare local variables
        • let mut personName:String;
          let mut bibleTranslation:String;
          let mut emptyStringLocal:String;
    • Initialize Variables
      • Initialize empty vector
        • list_of_Congregant = vec![];
    • Create structures
      • Set Local Variables
        // Create struct with field init shorthand
        personName = String::from("Peter Johnson");
        bibleTranslation = String::from("KJV");
        emptyStringLocal = emptyString.to_owned();
      • Initialize structure
        let peterJohnson = Congregant
        {
              personName: personName
            , bibleTranslation : bibleTranslation
            , isKJV : isKJV_false
            , err: emptyStringLocal
        };
        

 

Code Snippet


/*
    Import Traits
*/
use std::error::Error;

/*
    Declare Constants
*/
const emptyString:&str = "";
const isKJV_false:bool = false;
    
/*
    Declare structure Congregant
*/

#[derive(Debug)]
struct Congregant 
{
      personName: String
      
    , bibleTranslation: String
    
    , isKJV: bool
    
    , err:String
    
}

/*
    listView
*/
fn listView(list_of_Congregant:Vec<Congregant>)
{
   
    for (i, x) in list_of_Congregant.iter().enumerate() 
    {
    
          println!
          (
              "{:0?}) {:0?}"
            , i
            , x
          );
          
          println!("");
          
    }
    
}

/*
    listEvaluate
*/
fn listEvaluate
(
    list_of_Congregant:&mut Vec<Congregant>
)
{
  
    /*
        Declare function return variable
    */
    let mut isKJV_context:Result<bool, Box<dyn Error>>;
    
    let mut isKJV:bool = false;
    
    let mut bibleTranslationLocal:String;
    
    let mut errLocal:String;
    
    /*
        Iterate list
            Mutatable List
                iter() versus iter_mut() 
    */
    for x in list_of_Congregant.iter_mut() 
    {
    
        //reset context variables
        
             //set local error
            errLocal = "".to_string();
        
        //get a copy of bible name
        bibleTranslationLocal = x.bibleTranslation.to_owned();
        
        // determine if bible is KJV?
        isKJV_context = bibleIsKJV(bibleTranslationLocal);
        
        
        /*
            If return variable is OK, then it is usable
        */
        if isKJV_context.is_ok()
        {
      
           // Consume the result and return the contents with `unwrap`.
           isKJV = isKJV_context.unwrap();
           
        }      

        else if isKJV_context.is_err()
        {

          isKJV = false;

          //unwrap Error
          let err = isKJV_context.unwrap_err();
          
          //save errorLocal
          errLocal = err.to_string()
          
        }
        
        //save test
        x.isKJV = isKJV;
        
        //save exception
        x.err = errLocal;
        
        
          
    } //for 
    
}


fn bibleIsKJV
(
     bibleTranslation:String
) -> Result<bool, Box<dyn Error>>
{

    let errorMessage:String;
    
    /*
        If bible name is not KJV, raise exception
    */
    if bibleTranslation != "KJV"
    {
      
      errorMessage = format!
                        (
                              "Bible is not KJV.  It is '{0}'"
                            , bibleTranslation
                        );
                        
      //raise informative error
      //convert string to err type
       return Err
            (
                errorMessage.into()
            );
            
    }
    
    //return OK and true (as result)
    return Ok(true);
    
}

fn main() 
{
   
    //declare list
    let mut list_of_Congregant: Vec<Congregant>;
    
    let mut personName:String;
    let mut bibleTranslation:String;
    let mut emptyStringLocal:String;
       
    //initialize empty vector
    list_of_Congregant = vec![];
    
    // Create struct with field init shorthand
    personName = String::from("Peter Johnson");
    bibleTranslation = String::from("KJV");
    emptyStringLocal = emptyString.to_owned();

    //Initialize structure
    let peterJohnson = Congregant 
                            { 
                                  personName: personName
                                , bibleTranslation : bibleTranslation
                                , isKJV : isKJV_false
                                , err: emptyStringLocal 
                            };
                           
    //Add structure to list 
    list_of_Congregant.push(peterJohnson);
    
    // Create struct with field init shorthand
    personName = String::from("Sylvia Brown");
    bibleTranslation = String::from("The Passion Translation");
    emptyStringLocal = emptyString.to_owned();
    
    //Initialize structure    
    let sylviaBrown = Congregant
                      { 
                              personName: personName
                            , bibleTranslation : bibleTranslation
                            , isKJV : isKJV_false
                            , err: emptyStringLocal
                      };
                          
    //Add structure to list                             
    list_of_Congregant.push(sylviaBrown);
    
       // Create struct with field init shorthand
    personName = String::from("Paul Young");
    bibleTranslation = String::from("NIV");
    emptyStringLocal = emptyString.to_owned();
    
    //Initialize structure    
    let paulYoung = Congregant
                    { 
                          personName: personName
                        , bibleTranslation : bibleTranslation
                        , isKJV : isKJV_false
                        , err: emptyStringLocal
                    };
                          
    //Add structure to list                             
    list_of_Congregant.push(paulYoung);
    
    //evaluate list of congregants
    listEvaluate
    (
        &mut list_of_Congregant
    );
    
    //list congregants
    listView
    (
        list_of_Congregant
    );
    
    
    
}



Output

OnlineGDB

Image

Textual


In position 0 we have value Congregant { name: "Peter Johnson", bible: "KJV", isKJV: true, err: "" }
In position 1 we have value Congregant { name: "Sylvia Brown", bible: "Passion Edition", isKJV: false, err: "Bible is not KJV. It is 'Passion Edition'" }

Online Code IDE

OnlineGDB

  1. RustKJVOnly
    Link

Source Code Control

GitLab

  1. Rust – Exception Handling
    • Link
      Link
    • Files
      • 01) RustKJVOnly.rs

Summary

In this post, reviewed the data returned from our function.

  1. Returned Value
    • if is_ok()
      • unwrap function
        • retrieved returned value via the unwrap function
    • if is_err()
      • unwrap_err function
        • retrieved error value via the unwrap_err function

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s