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

traits and associated-types

Chris Morgan
Jul 15, 2015
<p>Here’s the correct code:</p> <pre><code>pub trait Person {} pub trait Directory { type Person: Person; fn get_person(&amp;self) -&gt; Self::Person; } pub trait Catalog { type Dir: Directory; fn get_directory(&amp;self) -&gt; Self::Dir; } fn do_something&lt;C: Catalog&gt;(catalog: C) { let directory = catalog.get_directory(); let person = directory.get_person(); do_something_with_person(person); } fn do_something_with_person&lt;P: Person&gt;(p: P) {} </code></pre> <p><code>&lt;P: Person&gt;</code> is generics syntax. Associated type definitions do not use generic syntax.</p> <p>Go for the full name in general; don’t abbreviate it <code>Per</code>, leave it <code>Person</code>. It’s always qualified (<code>Directory::Person</code>, <code>C::Person</code>, <em>&amp;c.</em>), so there’s no ambiguity. (<code>Dir</code> is an acknowledged short form of <code>Directory</code>, so there I guess either would be acceptable. I’d probably tend to go with <code>Directory</code>, however.)</p> <p>There’s no need to have the associated type <code>Person</code> specified on <code>Catalog</code>, either; <code>Self::Dir::Person</code> will do.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/31243253/traits%20and%20associated-types/31243642">Stack Overflow</a>.</p>
comments powered by Disqus