0

An answer to What is the difference between &Trait and impl Trait when used as method arguments? states:

If the actual type of your object only becomes known at runtime, this is the only version you can use, since you need to use dynamic dispatch

When would you not know the type at compile time? Seeing as the Rust compiler checks if a type meets the trait with &T1, wouldn't it also know its concrete type?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
zino
  • 1,222
  • 2
  • 17
  • 47

1 Answers1

3

Here's an example:

use rand::{thread_rng, Rng};

struct ConcreteA { }
struct ConcreteB { }

trait Trait { }

impl Trait for ConcreteA { }
impl Trait for ConcreteB { }

fn main() {
    // a runtime value
    let cond: bool = thread_rng().gen();

    let a = ConcreteA { };
    let b = ConcreteB { };
    
    let r: &dyn Trait = if cond { &a } else { &b };
}

What would be the concrete type that r refers to?

Trait constraints are checked by the compiler at the points where the &dyn Trait is created, since it must refer to a concrete type. The rest of the code can use the reference without knowing the concrete type by using dynamic dispatch. So the compiler always knows it refers to a concrete type but not necessarily which one.

kmdreko
  • 42,554
  • 6
  • 57
  • 106