4

这是我的代码:

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
}

v.push(x)引发此错误:

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>>>`

但是,如果我将值(用完全相同的值和类型构造)直接推送到向量中,它会编译而不会出错。

那么为什么第一个版本不编译呢?我应该改变什么才能使它x在推入向量之前可以使用?

4

1 回答 1

8

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

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

Rust 可以从该上下文中看出 to 的参数RefCell::new()必须是 a Box<dyn Trait>,因此尽管提供了 a Box<E>,它还是将其强制为前一种类型。另一方面,当您编写此代码时:

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

Rust 首先推断x类型的Rc<RefCell<Box<E>>>,你不能再把push它变成 a vecof Rc<RefCell<Box<dyn Trait>>>。您可以通过在let绑定中添加显式类型注释来更改此设置,以预先告诉 Rust 您确实需要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
}

操场

这里要理解的重要一点是,它E dyn Trait. E是一些已知的具体实现Traitwhiledyn Trait是一个特征对象,其底层具体实现已被删除。

于 2020-05-23T13:03:15.530 回答