{"id":2435,"date":"2022-04-23T13:05:57","date_gmt":"2022-04-23T18:05:57","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=2435"},"modified":"2022-04-23T13:06:00","modified_gmt":"2022-04-23T18:06:00","slug":"rust-fix-doesnt-implement-std-fmt-display","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/","title":{"rendered":"How to Fix `T` doesn&#8217;t implement std:fmt:Display in Rust?"},"content":{"rendered":"\n<p>Developers who come from a JavaScript background, or any other high-level programming language, and are learning Rust might find this language to have a steep learning curve. Oftentimes, many new Rust developers will come across the error <code>doesn't implement std:fmt:Display<\/code> when attempting to print a value that is not a string, like the one we see in the following example.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let mut array_cities: Vec&lt;String&gt; = Vec::new();\n    array_cities.push(\"San Francisco\".to_string());\n    array_cities.push(\"Santo Domingo\".to_string());\n\n    print!(\"testing {}\", array_cities); \/\/ It will error here\n}<\/code><\/pre>\n\n\n\n<p>If you attempt to execute this piece of logic using <code>cargo run<\/code> it will fail during compilation and will throw an error message similar to the following.<\/p>\n\n\n\n<pre class=\"wp-block-code language-bash\"><code>error&#91;E0277]: `Vec&lt;String&gt;` doesn't implement `std::fmt::Display`\n  --&gt; src\\main.rs:12:26\n   |\n12 |     print!(\"testing {}\", array_cities);\n   |                          ^^^^^^^^^^^^ `Vec&lt;String&gt;` cannot be formatted with the default formatter\n   |\n   = help: the trait `std::fmt::Display` is not implemented for `Vec&lt;String&gt;`\n   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead\n   = note: this error originates in the macro `$crate::format_args` (in Nightly builds, run with -Z macro-backtrace for more info)<\/code><\/pre>\n\n\n\n<p>This can be a little discouraging to most JavaScript developers who are used to logging just about anything using <code>console.log<\/code>, regardless of whether the data type of value to log in the terminal was a string, a number, an array, or any other data type, like you can see in the following example.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"459\" height=\"166\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/04\/Using-console.log-with-any-data-type-in-JavaScript.png\" alt=\"\" class=\"wp-image-2437\" title=\"Using console.log with any data type in JavaScript\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/04\/Using-console.log-with-any-data-type-in-JavaScript.png 459w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/04\/Using-console.log-with-any-data-type-in-JavaScript-300x108.png 300w\" sizes=\"auto, (max-width: 459px) 100vw, 459px\" \/><figcaption>Using console.log with any data type in JavaScript<\/figcaption><\/figure><\/div>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/#Data_Type_Must_Implement_Display_trait_std_fmt_Display\" >Data Type Must Implement Display trait (std::fmt::Display)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/#Implementing_Display_Trait_to_Data_Types\" >Implementing Display Trait to Data Types<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/#Cannot_Implement_Traits_Outside_of_the_Data_Type_Crate\" >Cannot Implement Traits Outside of the Data Type Crate<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/#Solution_Generate_a_Wrapper_Struct_to_Implement_Trait\" >Solution: Generate a Wrapper Struct to Implement Trait<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Data_Type_Must_Implement_Display_trait_std_fmt_Display\"><\/span>Data Type Must Implement <a href=\"https:\/\/doc.rust-lang.org\/std\/fmt\/trait.Display.html\" target=\"_blank\" rel=\"noreferrer noopener\">Display trait (std::fmt::Display)<\/a><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>To fix the error <code>doesn't implement std:fmt:Display<\/code> in Rust, make sure the data type contains the<a href=\"https:\/\/doc.rust-lang.org\/reference\/items\/implementations.html\" target=\"_blank\" rel=\"noreferrer noopener\"> implementation (<code>impl<\/code>)<\/a> of <code>fmt:Display<\/code>. <\/strong>For example, if we attempt to log a <a href=\"https:\/\/doc.rust-lang.org\/std\/string\/struct.String.html\" target=\"_blank\" rel=\"noreferrer noopener\">String <\/a>data type using either <code>print!<\/code> or <code>println!<\/code> macros, the code will successfully compile and log the value in the terminal.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let my_string = \"Hello Fellow Rustacean\".to_string();\n    print!(\"Logging my_string {}\", my_string);\n}<\/code><\/pre>\n\n\n\n<p>In this case, the variable <code>my_string<\/code> is logged not because it is a String, but because the <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/1e9aa8a96b207668799365bf891a459b62410b60\/library\/alloc\/src\/string.rs#L2213-L2218\" target=\"_blank\" rel=\"noreferrer noopener\">String data type, which is a built-in struct, has an implementation of <code>fmt:Display<\/code> as you can see in the source code<\/a> below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>impl fmt::Display for String {\n    #&#91;inline]\n    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {\n        fmt::Display::fmt(&amp;**self, f)\n    }\n}<\/code><\/pre>\n\n\n\n<p>If the String type wouldn&#8217;t have the implementation Display trait, it wouldn&#8217;t be possible to log its value using the <code>print!<\/code> macro.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Implementing_Display_Trait_to_Data_Types\"><\/span>Implementing Display Trait to Data Types<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Remember when we attempted to log a <a href=\"https:\/\/doc.rust-lang.org\/std\/vec\/struct.Vec.html\" target=\"_blank\" rel=\"noreferrer noopener\">Vec&lt;T&gt;<\/a>, but we came across with the error <code>Vec&lt;string&gt;doesn't implement std:fmt:Display<\/code>? Here&#8217;s the snippet of code to refresh your memory.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>fn main() {\n    let mut array_cities: Vec&lt;String&gt; = Vec::new();\n    array_cities.push(\"San Francisco\".to_string());\n    array_cities.push(\"Santo Domingo\".to_string());\n\n    print!(\"testing {}\", array_cities); \/\/ It will error here\n}<\/code><\/pre>\n\n\n\n<p>Now you know it is because the growable array (Vec&lt;T&gt;) hasn&#8217;t implemented the Display trait. <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/master\/library\/alloc\/src\/vec\/mod.rs\" target=\"_blank\" rel=\"noreferrer noopener\">If you are extra curious about this, you can always verify the set of implementations assigned to the Vec struct in the Rust source code<\/a>.<\/p>\n\n\n\n<p>In case you decide to check the source code, simply do a simple search (<code>Ctrl<\/code>+<code>F<\/code>) once you open the page and look for <em>fmt::Display for Vec<\/em>. You will find there are no results.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Cannot_Implement_Traits_Outside_of_the_Data_Type_Crate\"><\/span>Cannot Implement Traits Outside of the Data Type Crate<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The solution is to implement the Display Trait to Vec&lt;T>.  However, there is a small problem. <strong>We can only implement the Display Trait as long as we are in the same crate where the Vec&lt;T> is defined<\/strong>. <\/p>\n\n\n\n<p>This means we would have to implement this trait in <a href=\"https:\/\/github.com\/rust-lang\/rust\/blob\/master\/library\/alloc\/src\/vec\/mod.rs\" target=\"_blank\" rel=\"noopener\">Vec&lt;T&gt; crate<\/a>. Technically, we could make those changes locally, but it means overriding the Rust source code, which is not recommended.<\/p>\n\n\n\n<p>On top of that, you would have to manually update this code every time the rust library is installed in the directory, which is not an ideal solution when attempting to make automated deployments.  <\/p>\n\n\n\n<p>In other words,<strong> it is not possible to implement the Display trait in Vec&lt;T&gt; in our crate.<\/strong>  <\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Solution_Generate_a_Wrapper_Struct_to_Implement_Trait\"><\/span>Solution: Generate a Wrapper Struct to Implement Trait<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Luckily, there is a workaround for this: to generate a wrapper or custom struct which uses a data type defined outside the crate. Once the struct is created, implement the Display trait.<\/p>\n\n\n\n<p>In the following example, we are going to define the struct <code>WrapperVec<\/code> to contain <code>cities<\/code> which is the <code>Vec&lt;String><\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>struct WrapperVec {\n    cities: Vec&lt;String&gt;\n}<\/code><\/pre>\n\n\n\n<p>Once the <code>WrapperVec<\/code> is created, implement the Display trait to the new struct. For the sake of simplicity, we are only going to log the text <em>Cities<\/em>! rather the values that could be stored in <code>WrapperVec.cities<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>use std::fmt;\n\nimpl fmt::Display for WrapperVec {\n    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {\n        write!(f, \"Cities!\")\n    }\n}<\/code><\/pre>\n\n\n\n<p>Now, if we update our <code>main<\/code> function to use a <code>WrapperVec<\/code> struct and log (<code>print!<\/code>) its value, we no longer see the error <code>doesn't implement std:fmt:Display<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>use std::fmt;\n\nfn main() {\n    let mut array_cities: Vec&lt;String&gt; = Vec::new();\n    array_cities.push(\"San Francisco\".to_string());\n    array_cities.push(\"Santo Domingo\".to_string());\n\n    let wrapper_vec = WrapperVec {\n        cities: array_cities,\n    };\n\n    print!(\"testing {}\", wrapper_vec);\n}\n\nstruct WrapperVec {\n    cities: Vec&lt;String&gt;\n}\n\nimpl fmt::Display for WrapperVec {\n    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {\n        write!(f, \"Cities!\")\n    }\n}. <\/code><\/pre>\n\n\n\n<p>Unfortunately, the <code>fmt<\/code> function doesn&#8217;t display the elements of the growable array. <\/p>\n\n\n\n<p>At this point, we can update the logic of the <code>fmt<\/code> function to iterate through each of the elements of the Vec&lt;String> array and list each city, or any value, defined in the program.<\/p>\n\n\n\n<pre class=\"wp-block-code language-rust\"><code>impl fmt::Display for WrapperVec {\n    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {\n        writeln!(f, \"Cities found!\")?;\n\n        for city in self.cities.iter() {\n            writeln!(f, \"- {}\", city)?;\n        }\n\n        write!(f, \"Done!\")\n    }\n}<\/code><\/pre>\n\n\n\n<p>If you updated the code using the previous example and execute it, you should see an output similar to the following screenshot. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2022\/04\/Final-output-after-implement-Display-trait-to-wrapper-struct.png\" alt=\"\" class=\"wp-image-2438\" width=\"612\" height=\"91\" title=\"Final output after implement Display trait to wrapper struct\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/04\/Final-output-after-implement-Display-trait-to-wrapper-struct.png 612w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2022\/04\/Final-output-after-implement-Display-trait-to-wrapper-struct-300x45.png 300w\" sizes=\"auto, (max-width: 612px) 100vw, 612px\" \/><figcaption>Final output after implementing Display trait to wrapper struct<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All in all, the reason behind getting the error <code>doesn't implement std:fmt:Display<\/code> is that the data type doesn&#8217;t have implemented the Display trait. To solve this you should either use a data type that does implement the Display trait or implement the trait to the data type that you are attempting to use in the code.<\/p>\n\n\n\n<p><strong>Did you learn something new?<\/strong><\/p>\n\n\n\n<p>I hope this article helped you understand a common error new Rust programmers tend to come across, and also learn how to fix it.<\/p>\n\n\n\n<p>Share your thoughts by replying on <a href=\"https:\/\/twitter.com\/bbprogrammer\" target=\"_blank\" rel=\"noreferrer noopener\">Twitter of Become A Better Programmer<\/a> or to <a href=\"https:\/\/twitter.com\/arealesramirez\" target=\"_blank\" rel=\"noreferrer noopener\">my personal Twitter account<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Developers who come from a JavaScript background, or any other high-level programming language, and are learning Rust might find this language to have a steep learning curve. Oftentimes, many new Rust developers will come across the error doesn&#8217;t implement std:fmt:Display when attempting to print a value that is not a string, like the one we &#8230; <a title=\"How to Fix `T` doesn&#8217;t implement std:fmt:Display in Rust?\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/rust-fix-doesnt-implement-std-fmt-display\/\" aria-label=\"More on How to Fix `T` doesn&#8217;t implement std:fmt:Display in Rust?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":2448,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[31],"tags":[],"class_list":["post-2435","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-rust","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2435","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=2435"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2435\/revisions"}],"predecessor-version":[{"id":2449,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/2435\/revisions\/2449"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/2448"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=2435"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=2435"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=2435"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}