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

Matching with less boilerplate

Chris Morgan
Jul 15, 2015
<p>Given these definitions:</p> <pre><code>enum X { Variant(Y), … } enum Y { Variant(Z), … } struct Z; </code></pre> <p>You can use <code>if let</code> with deep patterns as one way:</p> <pre><code>if let X::Variant(Y::Variant(ref z) = x { // Use z } else { // And these two lines are, panic!(); // of course, optional. } </code></pre> <p>Or you could define methods (panicking is not a good idea, though; having such methods return <code>Option</code> is much more common, as is shown in rustc_serialize’s <code>Json</code> enum, for example), but it will still leave you with comparatively ugly code, probably):</p> <pre><code>impl X { fn y(&amp;self) -&gt; &amp;Y { match *self { Variant(ref y) =&gt; y, _ =&gt; panic!(), } } } // Ditto for Y.z() let z = x.y().z(); </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31177437/Matching%20with%20less%20boilerplate/31178537">Stack Overflow</a>.</p>
comments powered by Disqus