此问题源自另一个问题: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 Trait
到impl Trait
有什么区别?
我解决了问题:
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));
}
}