Rust:- Formatted Output – Writeln! and Format! – Span Multiple Lines

Background

In this post we will quickly cover how to span a string across multiple lines in Rust.

We will employ the back slash ( \ ) at the end of each line that will be succeded.

 

Script

Outline

  1. In Rust to span a string across multiple lines, please use the back slash at the end of each line ( \ ) to indicate that the line continues
  2. The string continues on the next line’s first non white-space character

Pictoral

SingleLine

MultiLine

Code

Snippet

Structure

PersonAddress

/*
    Declare Structure person_address
*/
#[derive(Debug)]
struct PersonAddress
{
      person_name: String
      
    , street_address: String
    
    , city:String
    
    , state:String
    
    , postal_code:String
    
}

Implementation

Debug
PersonAddress


impl std::fmt::Display for PersonAddress
{

	fn fmt
	(
		&self, f: &mut std::fmt::Formatter
	) -> std::fmt::Result 
	{
		
		let buffer:String;	
		
		if DISPLAY_TYPE_MULTI_LINE == false
		{
			buffer = format!
				(
					  "\t{0}\n\tStreet Address:- {1}\n\tCity:- {2}\n\tState:- {3}\n\tPostal Code:- {4}"
					  
					, self.person_name
					
					, self.street_address
					
					, self.city
					
					, self.state
					
					, self.postal_code
					
				);
		}
		else 
		{
			buffer = format!
				(
					  "\t{0}\n\
					  \tStreet Address:- {1}\n\
					  \tCity:- {2}\n\
					  \tState:- {3}\n\
					  \tPostal Code:- {4}\n\
					  "

					, self.person_name
					
					, self.street_address
					
					, self.city
					
					, self.state
					
					, self.postal_code
				);
		}
			
		let result =
					writeln!
					(
						  f
						, "{}"  
						, buffer
					);
					
		return result;
		
	}

	
}

Output

Image

Textual


Debug
*****
PersonAddress { person_name: "Quincy Jones", street_address: "1819 Browne Street", city: "Chicago", state: "Illinois", postal_code: "60007" }

PersonAddress { person_name: "Siedah Garrett", street_address: "117 Hawthorne Lane", city: "Los Angeles", state: "California", postal_code: "90001" }


Display
*******
        Quincy Jones
        Street Address:- 1819 Browne Street
        City:- Chicago
        State:- Illinois
        Postal Code:- 60007



        Siedah Garrett
        Street Address:- 117 Hawthorne Lane
        City:- Los Angeles
        State:- California
        Postal Code:- 90001



Online Source Code

OnlineGDB

  1. rustStructPersonAddressUseofFormatAcrossMultipleLines.rs
    Link

 

 

References

  1. rust-lang.org
    • In Std
      • Macro
        • Macro std::println
          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