× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Using Formatter::debug_list to implement Debug for a two-dimensional array

Chris Morgan
Jul 15, 2015
<p><code>entry()</code> is defined thus:</p> <pre><code>pub fn entry(&amp;mut self, entry: &amp;fmt::Debug) -&gt; &amp;mut DebugList&lt;'a, 'b&gt;; </code></pre> <p>It takes a <code>fmt::Debug</code> <em>trait object</em>. Thus when you pass it a <code>&amp;[T]</code>, it wants to cast it implicitly to <code>&amp;fmt::Debug</code>. This, however, cannot be done, for trait objects can only be constructed of sized objects. The solution is to make a trait object of the sized slice; that is, pass something of type <code>&amp;&amp;[T]</code> which can then be implicitly converted to <code>&amp;fmt::Debug</code>, containing the type <code>&amp;[T]</code>. That is, <code>b.entry(&amp;e)</code> instead of <code>b.entry(e)</code>.</p> <p>Your <code>builder</code> line is unnecessary too and actually introduces lifetime problems; you should declare it as part of the <code>fold</code> call for convenience.</p> <p>This leaves you with this as your final result:</p> <pre><code>impl&lt;T: fmt::Debug&gt; fmt::Debug for Array2&lt;T&gt; { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { self.rows().fold(&amp;mut f.debug_list(), |b, e| b.entry(&amp;e)).finish() } } </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31348281/Using%20Formatter::debug_list%20to%20implement%20Debug%20for%20a%20two-dimensional%20array/31353422">Stack Overflow</a>.</p>
comments powered by Disqus