Rust:- Formatting Expressions

Background

Let us share some of the formatting expressions that are supported in Rust.

 

Format Macros

Macro Intent Example
format! Emits output to a string let buffer:String;
buffer = format!(“{0} plus {1} equals {2}”, 1,2, 1+2);
write! Emits output to a file handle
writeln! Emits output to a file handle and adds a new line
print! Emits output to standard output
println! Emits output to standard output and adds a new line println!(“{0:10.3}”, 22 as f64 / 7 as f64);
eprint! Emits output to standard error
eprintln! Emits output to standard error and adds a new line let filename:&str = “b:\\fileNoPresent.txt”;
eprintln!(“Error: Could not openfile {0}”, filename);
format_args! Used to pass around a format strings

 

Building Out a Format String

Positional Parameters

In bare, a format tag is repersented as {}.

Based on which argument will be represented it’s place in the argument list is referenced.

The first argument is 0 (zero ).

Here is a basic example:-


println!
(
     "Number 1 ( {0} ) divide Number 2 ( {1} ) is {2}"
   , number_1_float
   , number_2_float
   , result_float
);

Explanation:-

  1. {0}:- number_1_float
  2. {1}:- number_2_float
  3. {2}:- result_float

 

Formatting Tags

Data Type Intent Expression Result
Float
Plain number {2} 3.142857142857143
three (3) decimal places {2:.3} 3.143
width of 10, and three (3) decimal places {2:10.3}       3.143
width of 10 – 0 left padded, and three (3) decimal places {2:010.3} 000003.143
String
Character size 15, left  ( < ) aligned [{4:<15}] [55101 ]
Character size 15, right  ( < ) aligned [{4:>15}] [ 55101]
Character size 15, middle  ( < ) aligned [{4:^15}] [ 55101 ]

 

Script

Code


/*
    Declare "Module" Constants
*/
const CHAR_EQUAL:char = '=';

fn repeatChar(ch: char, n:usize) -> String
{
    return
         
       (
            ch.to_string()
       ).repeat(n);
         
}

fn main() 
{

    let number_1_float:i32 = 22;
    let number_2_float:i32 = 7;
    let result_float:f64;
    
    let mut format:String;
    
    let header_address_fullname:&str = "Name";
    let header_address_address:&str = "Address";
    let header_address_city:&str = "City";
    let header_address_state:&str = "State";
    let header_address_postal_code:&str = "Postal Code";
    
    
    let header_address_fullname_underline:String
            = repeatChar
                (
                      CHAR_EQUAL
                    , header_address_fullname.chars().count()
                ).to_string();
                
    let header_address_address_underline:String
        = repeatChar
                (
                      CHAR_EQUAL
                    , header_address_address.chars().count()
                ).to_string();
    
    let header_address_city_underline:String
        = repeatChar
                (
                      CHAR_EQUAL
                    , header_address_city.chars().count()
                ).to_string();
    
    let header_address_state_underline:String
        = repeatChar
                (
                      CHAR_EQUAL
                    , header_address_state.chars().count()
                ).to_string();
    
    let header_address_postal_code_underline:String
        = repeatChar
                (
                      CHAR_EQUAL
                    , header_address_postal_code.chars().count()
                ).to_string();
    
    
    let mut fullname_1:&str;
    let mut address_1:&str;
    let mut city_1:&str;
    let mut state_1:&str;
    let mut postal_code_1:&str;
    
    
    
    let mut fullname_2:&str;
    let mut address_2:&str;
    let mut city_2:&str;
    let mut state_2:&str;
    let mut postal_code_2:&str;    
    
    
    
    result_float = number_1_float as f64 / number_2_float as f64 ;
    
    
    fullname_1 = "John Smith";
    address_1 = "1021 Brinson Street";
    city_1 = "St Paul";
    state_1 = "MN";
    postal_code_1 = "55101";
    
    
    fullname_2 = "Angie Stone";
    address_2 = "7181 Ridgewood Drive";
    city_2 = "Rochestor";
    state_2 = "NY";
    postal_code_2 = "14602";   
    
    
    println!(
                  "Number 1 ( {0} ) divide Number 2 ( {1} ) is {2}"
                , number_1_float
                , number_2_float
                , result_float
            );
            
    println!();
    
    /*
        {Position:.3}
    */
    format=r"position:.decimalPlaces ( {2:.3} )".to_string();
    println!(
                  "Number 1 ( {0} ) divide Number 2 ( {1} ) is {2:.3}.  \
                  Format as {3}"
                , number_1_float
                , number_2_float
                , result_float
                , format
            );   
            
    println!();        
            
    /*
        format!("{:04}", 42);             // => "0042" with leading zeros
    */
    format=r"position:length.decimalPlaces ( {2:10.3} )".to_string();
    
    println!(
                  "Number 1 ( {0} ) divide Number 2 ( {1} ) is {2:10.3}.  \
                  Format as {3}"
                , number_1_float
                , number_2_float
                , result_float
                , format
            );   
            
    println!();

    /*
        Left Align
    */ 
    println!("Left Justify");
    println!();
    
    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname
                , header_address_address
                , header_address_city
                , header_address_state
                , header_address_postal_code
            ); 
            
      
    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname_underline
                , header_address_address_underline
                , header_address_city_underline
                , header_address_state_underline
                , header_address_postal_code_underline
            ); 
                        

    println!(
                  "{:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , fullname_1
                , address_1
                , city_1
                , state_1
                , postal_code_1
            ); 
            


    println!(
                  "{:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , fullname_2
                , address_2
                , city_2
                , state_2
                , postal_code_2
            );   
            
    println!();
    println!();
    
    /*
        Right Align
    */
    println!("Right Justify");
    println!();   
    
    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname
                , header_address_address
                , header_address_city
                , header_address_state
                , header_address_postal_code
            ); 
            

    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname_underline
                , header_address_address_underline
                , header_address_city_underline
                , header_address_state_underline
                , header_address_postal_code_underline
            ); 
                                
    println!(
                  "{:>30} {1:>30} {2:>25} {3:>10} {4:>15}"
                , fullname_1
                , address_1
                , city_1
                , state_1
                , postal_code_1
            ); 
                        
    println!(
                  "{:>30} {1:>30} {2:>25} {3:>10} {4:>15}"
                , fullname_2
                , address_2
                , city_2
                , state_2
                , postal_code_2
            ); 
            
    println!();
    println!();
    
    /*
        Center Align
    */
    println!("Center Justify");
    println!();
        
    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname
                , header_address_address
                , header_address_city
                , header_address_state
                , header_address_postal_code
            ); 
            

    println!(
                  "{0:<30} {1:<30} {2:<25} {3:<10} {4:<15}"
                , header_address_fullname_underline
                , header_address_address_underline
                , header_address_city_underline
                , header_address_state_underline
                , header_address_postal_code_underline
            ); 
                                
    println!(
                  "{:^30} {1:^30} {2:^25} {3:^10} {4:^15}"
                , fullname_1
                , address_1
                , city_1
                , state_1
                , postal_code_1
            ); 
                        
    println!(
                  "{:^30} {1:^30} {2:^25} {3:^10} {4:^15}"
                , fullname_2
                , address_2
                , city_2
                , state_2
                , postal_code_2
            ); 
                        
    println!();
    println!();
    
            
            
}


Output

Image

Textual


Number 1 ( 22 ) divide Number 2 ( 7 ) is 3.142857142857143

Number 1 ( 22 ) divide Number 2 ( 7 ) is 3.143.  Format as position:.decimalPlaces ( {2:.3} )

Number 1 ( 22 ) divide Number 2 ( 7 ) is      3.143.  Format as position:length.decimalPlaces ( {2:10.3} )

Left Justify

Name                           Address                        City                      State      Postal Code    
====                           =======                        ====                      =====      ===========    
John Smith                     1021 Brinson Street            St Paul                   MN         55101          
Angie Stone                    7181 Ridgewood Drive           Rochestor                 NY         14602          


Right Justify

Name                           Address                        City                      State      Postal Code    
====                           =======                        ====                      =====      ===========    
                    John Smith            1021 Brinson Street                   St Paul         MN           55101
                   Angie Stone           7181 Ridgewood Drive                 Rochestor         NY           14602


Center Justify

Name                           Address                        City                      State      Postal Code    
====                           =======                        ====                      =====      ===========    
          John Smith                1021 Brinson Street                St Paul              MN          55101     
         Angie Stone                7181 Ridgewood Drive              Rochestor             NY          14602     



Online Source Code

OnlineGDB

  1. rustFormatExpressions.rs
    Link

 

Source Code Control

GitLab

  1. Rust – Formatting Expressions
    Link

    • Files
      rust_format_expressions_day_01.rs

 

 

References

  1. doc.rust-lang.org
    • Module std::fmt
      Link
  2. In Std
    • Macro std::format
      Link

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