什么时候类型只在运行时才知道?

When is a type only known at runtime?

的回答指出:

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

编译时什么时候不知道类型?既然 Rust 编译器检查一个类型是否满足 &T1 的特征,难道它不也知道它的具体类型吗?

这是一个例子:

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 };
}

r 指的具体类型是什么?

编译器在创建 &dyn Trait 时检查特征约束,因为它必须引用具体类型。其余代码可以通过使用动态调度在不知道具体类型的情况下使用引用。所以编译器总是知道它指的是 a 具体类型但不一定是哪个。