Skip to Content
Course content

191: Associated Types vs Generic Parameters

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably run into this while digging through the standard library: some traits look like Iterator<Item = T>, while others look like From<T>. On the surface, they both seem to be doing the same thing—letting the trait work with different types. But in practice, they serve two completely different architectural purposes.

Wait, why bother with associated types when I can just use a generic parameter?

The short answer is: associated types simplify your function signatures.

Imagine we're building a Graph library. If we used a generic parameter for the node type, the trait would look like this:

trait Graph<N> {
    fn add_node(&mut self, node: N);
    fn get_nodes(&self) -> Vec<N>;
}

Now, imagine you write a function that takes any graph and prints the nodes. Your signature becomes: fn print_nodes<G: Graph<N>, N>(graph: G). Notice how I had to introduce N as a generic parameter for the function itself, even though I don't actually care what N is? I just care that the graph knows what its own node type is.

If we use an associated type, it looks like this:

trait Graph {
    type Node;
    fn add_node(&mut self, node: Self::Node);
    fn get_nodes(&self) -> Vec<Self::Node>;
}

Now my function is just: fn print_nodes<G: Graph>(graph: G). The compiler knows that if G implements Graph, it must have exactly one Node type associated with it. I don't have to drag extra generic parameters around my entire codebase like a heavy suitcase.

Can I actually implement a trait multiple times if I use generics?

Yes, and that's exactly why generics exist in traits. This is the "killer feature" that associated types can't do.

With an associated type, you can only implement the trait once for a specific type. If MyGraph implements Graph with type Node = String, you cannot also implement Graph for MyGraph with type Node = i32. It's a 1:1 relationship.

But with generics, it's 1:Many. Look at the From<T> trait. I can implement From<u32> for my UserId struct, and I can also implement From<String> for that same UserId struct.

struct UserId(u32);

impl From<u32> for UserId {
    fn from(val: u32) -> Self { UserId(val) }
}

impl From<String> for UserId {
    fn from(val: String) -> Self { 
        // some parsing logic here
        UserId(val.parse().unwrap()) 
    }
}

If From used an associated type, you'd have to pick one single type that UserId could be created from, and that's just not how real-world data works.

How does this change how the compiler figures out types?

This is where the "magic" (and the frustration) happens. When you use an associated type, the implementing type determines the associated type. If I have a Vec<i32>, and it implements Iterator, the compiler knows immediately that the Item is i32.

With generics, the caller often determines the type. If I have a function fn convert<T, U>(input: T) where U: From<T>, the compiler can't know what U is just by looking at input. You usually have to provide a type hint, like let x: MyType = convert(input);.

I generally follow this rule of thumb: If the type is a "property" of the implementation (like the Item of an Iterator), use an associated type. If the type is an "input" or "target" that can vary (like the source type of a conversion), use a generic parameter.




📋 Practical Task

Implementing a Multi-Format Document Exporter

You are building a document system where a Document can be exported into multiple different formats (e.g., PDF, HTML, Markdown). Because a single document should be exportable to many different formats, you cannot use associated types for the format—you must use generic parameters.

Your Task:

  • Create a trait called Exportable<F> where F represents the output format. It should have one method: fn export(&self, format: F) -> String;
  • Create a struct Report that holds a title: String and content: String.
  • Create two empty structs: PdfFormat and HtmlFormat.
  • Implement Exportable<PdfFormat> for Report, returning a string that starts with "[PDF] ".
  • Implement Exportable<HtmlFormat> for Report, returning a string that starts with "[HTML] ".
  • In your main function, instantiate a Report and call export using both format types to prove that one struct can implement the trait multiple times.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.