Rust:- Data Structure – struct – print – display implementation ( fmt::Display )

Background

In Rust, let us cover how to print out the contents of the struct data structure.

In this post we will use the fmt::Display trait.

 

Lineage

  1. Rust:- Data Structure – struct – print – debug implementation ( fmt::Debug )
    Link

 

Definition Statement

Rust-Lang.org

Debug

Link

All types which want to use std::fmt formatting traits require an implementation to be printable.

Automatic implementations are only provided for types such as in the std library.

All others must be manually implemented somehow.

The fmt::Debug trait makes this very straightforward.

All types can derive (automatically create) the fmt::Debug implementation.

This is not true for fmt::Display which must be manually implemented.

 

Formatting Code

Type Format Specifier Sample Sample Explanation
Print {} {0} 0 means the first variable

 

Code

Original


struct Person
{
name: String
, age: u8
}
fn main()
{
// Create struct with field init shorthand
//String Literals ( static )
let nameHardCoded:&'static str = "Peter 1";
let age1 = 27;
let objPeter1 = Person
{
name:nameHardCoded.to_string()
, age:age1
};
//Print Person 1
println!
(
"{0}"
, objPeter1
);
}

Output

Output – Image

Output – Text


error[E0277]: `Person` doesn't implement `std::fmt::Display`
  --> main.rs:35:11
   |
35 |         , objPeter1
   |           ^^^^^^^^^ `Person` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `Person`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.

Explanation

The format string {0} relies on the Display method implementation.

As we are trying to emit a non-standard datatype, we will have to provide a homegrown implementation.

 

Revision

Outline

  1. We need a “Format Specifier” for the person structure
    • impl std::fmt::Display for Person

Add Format Specifier

Outline

  1. Function Name is fmt
  2. Function Argument
    • &self
    • variable name f
      • variable mutability is mut
        • &mut
        • That is we can change the contents of variable f
      • Variable Type is std::fmt::Formatter

Code


use std::fmt::{self, Formatter, Display};
/*
Specify that structure implements the Debug trait
i.e. we will be able to print structure contents by using {:?} specifier in our print statements
*/
//#[derive(Debug)]
struct Person
{
name: String
, age: u8
}
/*
Rust – How to print structs and arrays?
https://stackoverflow.com/questions/30253422/how-to-print-structs-and-arrays
All types can derive (automatically create) the fmt::Debug implementation as #[derive(Debug)],
but fmt::Display must be manually implemented.
You can create a custom output:
*/
impl std::fmt::Display for Person
{
fn fmt
(
&self, f: &mut std::fmt::Formatter
) -> std::fmt::Result
{
write!
(
f
, "Person ( name: \"{0}\", age: {1} )"
, self.name
, self.age
)
}
}
fn main()
{
// Create struct with field init shorthand
//String Literals ( static )
let nameHardCoded:&'static str = "Peter 1";
let age = 27;
let objPeter = Person
{
name:nameHardCoded.to_string()
, age:age
};
//Debug Basic Print Person 1
println!
(
"{0}"
, objPeter
);
//String Literals ( static )
let nameJohn = "John 2";
let objJohn = nameJohn.to_string();
let ageJohn = 29;
let objJohn = Person
{
name:objJohn
, age:ageJohn
};
//Debug Basic Print Person 1
println!
(
"{0}"
, objJohn
);
}

Output

Output – Image

Output – Text

struct - Person ( name: "Peter 1",  age: 27 )

Explanation

We provided the format specifier for our structure.

And, the println! method was able to use the provided function and properly print out our structure.

Online Software Development

OnlineGDB

  1. rustdatastructurestructprintdisplay.rs
    Link

 

References

  1. Rust By Example

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s