除非使用临时变量,否则为什么不能插入dyn Trait Vec?

这是我的代码:

use std::rc::{Rc, Weak};
use std::cell::RefCell;

trait Trait {}


fn push<E: Trait>(e: E) {
    let mut v: Vec<Rc<RefCell<Box<dyn Trait>>>> = Vec::new();

    // let x = Rc::new(RefCell::new(Box::new(e)));
    // v.push(x);  *error*

    v.push(Rc::new(RefCell::new(Box::new(e)))); // works fine
}

The v.push(x) raises the error:

error[E0308]: mismatched types
  --> src/main.rs:12:12
   |
7  | fn push<E: Trait>(e: E) {
   |         - this type parameter
...
12 |     v.push(x);
   |            ^ expected trait object `dyn Trait`, found type parameter `E`
   |
   = note: expected struct `std::rc::Rc<std::cell::RefCell<std::boxed::Box<dyn Trait>>>`
              found struct `std::rc::Rc<std::cell::RefCell<std::boxed::Box<E>>>`
   = help: type parameters must be constrained to match other types
   = note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters

但是,如果我推送临时值(由完全相同的值和类型构造),则编译时不会出现任何错误。

Why the first version doesn't compile? And what should I change it to make it so I can use x before pushing it ito the vector (for example downgrading it into a rc::Weak)?

评论
<午夜m>
<午夜m>

一切都在类型推断中。当你写:

v.push(Rc::new(RefCell::new(Box::new(e))));

Rust can tell from that context that the argument to RefCell::new() must be a Box<dyn Trait>, so despite supplying a Box<E>, it coerces it to the former type. When you write this on the other hand:

let x = Rc::new(RefCell::new(Box::new(e)));
v.push(x); // compile error

Rust first infers that x of type Rc<RefCell<Box<E>>> and you can no longer push it into a vec of Rc<RefCell<Box<dyn Trait>>>. You can change this by putting an explicit type annotation in your let binding to tell Rust upfront that you really do want a Rc<RefCell<Box<dyn Trait>>>:

use std::rc::{Rc, Weak};
use std::cell::RefCell;

trait Trait {}

fn push<E: Trait>(e: E) {
    let mut v: Vec<Rc<RefCell<Box<dyn Trait>>>> = Vec::new();

    let x: Rc<RefCell<Box<dyn Trait>>> = Rc::new(RefCell::new(Box::new(e)));
    v.push(x); // compiles
}

playground

The important thing to understand here is that E is not the same as dyn Trait. E is some known concrete implementation of Trait while dyn Trait is a trait object with its underlying concrete implementation erased.

点赞
评论