rust dyn特性vs impl特性

问题描述 投票:0回答:1

此问题源自另一个问题:rust pass box reference without move

背景:

我正在生锈中编写RDBMS。

有一个目录结构,用于维护从table_id到表的映射:

pub struct Catalog {
    table_id_table_map: HashMap<i32, Rc<dyn Table>>,
}

impl Catalog {
    pub(crate) fn add_table(&mut self, table: Rc<impl Table>, table_name: &str, primary_key: &str) {
        self.table_id_table_map.insert(table.get_id(), Rc::clone(&table));
    }
}

但是编译失败:

error[E0308]: mismatched types
  --> src/database.rs:45:66
   |
44 |     pub(crate) fn add_table(&mut self, table: Rc<impl Table>, table_name: &str, primary_key: &str) {
   |                                                  ---------- this type parameter
45 |         self.table_id_table_map.insert(table.get_id(), Rc::clone(&table));
   |                                                                  ^^^^^^ expected trait object `dyn table::Table`, found type parameter `impl Table`
   |
   = note: expected reference `&std::rc::Rc<dyn table::Table>`
              found reference `&std::rc::Rc<impl Table>`
   = 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

所以,从dyn Traitimpl Trait有什么区别?

rust traits
1个回答
0
投票

我解决了问题:

impl Catalog {
    pub(crate) fn add_table(&mut self, table: Rc<dyn Table>, table_name: &str, primary_key: &str) {
        self.table_id_table_map
            .insert(table.get_id(), Rc::clone(&table));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.