FAQ - Help and questions

What is the difference between generics with impl Trait and dyn Trait in Rust?

#traits#generics#basicspublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

A generic or impl Trait parameter is resolved at compile time. The compiler builds one version of the function per concrete type, which is fast but needs the type to be known. dyn Trait is resolved at run time through a pointer, so one function can handle a list of different types.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Both let a function work with "anything that implements a trait". They differ in when the choice is made.

src/main.rsrust
trait Shape {
    fn area(&self) -> f64;
}

struct Square(f64);
struct Circle(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}
impl Shape for Circle {
    fn area(&self) -> f64 {
        3.0 * self.0 * self.0 // 3.0 instead of pi, to keep the output short
    }
}

// Generic: the compiler makes one copy of the function per type (static dispatch).
fn print_area(shape: &impl Shape) {
    println!("area {}", shape.area());
}

// Trait object: one function, the method is looked up at run time (dynamic dispatch).
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}

fn main() {
    print_area(&Square(2.0));
    let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
    println!("total {}", total_area(&mixed));
}
text
area 4
total 7

The answers below describe the two approaches as separate, complete options.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: generics or impl Trait (static dispatch)#

    fn print_area(shape: &impl Shape) is shorthand for a generic function. The compiler creates a separate copy for each type you call it with, and each call is a direct call that can be inlined.

    Best when: the type is known where the call is written, and speed matters. Cost: all items in one Vec must be the same type, and more copies mean more compiled code.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: dyn Trait (dynamic dispatch)#

      Vec<Box<dyn Shape>> can hold a Square and a Circle side by side. A dyn value is always behind a pointer (Box, &, Rc) because its size is not known. Each call looks the method up in a table at run time.

      Best when: you need a mixed collection, a plugin-like list, or a stable function signature that hides the concrete type. Cost: one small indirection per call, and the trait must be "object safe" (no generic methods, for example).

      Common mistakes#

      • Writing Vec<Shape> or fn f(s: Shape) with a trait name alone. Since Rust 2021 this is an error; write impl Shape, &dyn Shape or Box<dyn Shape>.
      • Choosing dyn out of habit from other languages. Start with generics and switch when you really need a mixed list.
        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail