title: How to implement Display while respecting width, fill and alignment?
body: <p>I have a custom wrapper type <code>Length</code> for which I want to implement the <code>Display</code> trait. I also want it to respect the width, fill and alignment rules, which doesn't happen by default:</p>
  <pre><code>use std::fmt;
  
  struct Length(f64);
  
  impl fmt::Display for Length {
      fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
          write!(f, &quot;{:.1} m&quot;, self.0)
      }
  }
  
  fn main() {
      let l = Length(1.0);
      assert_eq!(format!(&quot;{}&quot;, l),    &quot;1.0 m&quot;);       // Passes
      assert_eq!(format!(&quot;{:10}&quot;, l), &quot;1.0 m     &quot;);  // Fails: padding is not added
      assert_eq!(format!(&quot;{:&gt;10}&quot;, l), &quot;     1.0 m&quot;); // Fails: padding is not added
  }
  </code></pre>
  <p>The <a href="https://doc.rust-lang.org/std/fmt/index.html#fillalignment" rel="nofollow noreferrer">docs</a> are explicit about this lack of global support:</p>
  <blockquote>
  <p>Note that alignment might not be implemented by some types. In particular, it is not generally implemented for the Debug trait. A good way to ensure padding is applied is to format your input, then pad this resulting string to obtain your output:</p>
  <pre><code>println!(&quot;Hello {:^15}!&quot;, format!(&quot;{:?}&quot;, Some(&quot;hi&quot;))); // =&gt; &quot;Hello   Some(&quot;hi&quot;)   !&quot;
  </code></pre>
  </blockquote>
  <p>But this workaround would have to be used in every place where a <code>Length</code> is being formatted. I don't want that.</p>
  <p>Of course I can implement it all by hand, but there must be a better way.</p>
  <p>I tried this naive way to reuse the <code>Display</code> features of <code>String</code>:</p>
  <pre><code>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {
          write!(f, &quot;{}&quot;, format!(&quot;{:.1} m&quot;, self.0))
      }
  </code></pre>
  <p>But of course it doesn't work, because the format string <code>&quot;{}&quot;</code> throws away all information that comes in through <code>f</code>.</p>