不带锈的通行箱参考

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

背景:

我正在生锈中编写RDBMS

db.catalog维护从table_id到表的哈希图:

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

并且当我将装箱的表添加到目录中时,发生了移动。然后我不能再使用表实例:

// create table
let table = create_random_heap_table(....);
// add to catalog
db.get_catalog().add_table(Box::new(table), "heap table", "");
// access table instance
let table_id = table.get_id();

编译错误:

error[E0382]: borrow of moved value: `table`
   --> src/lib.rs:113:32
    |
103 |                 let table = create_random_heap_table(
    |                     ----- move occurs because `table` has type `table::HeapTable`, which does not implement the `Copy` trait
...
111 |                 db.get_catalog().add_table(Box::new(table), "heap table", "");
    |                                                     ----- value moved here
112 | 
113 |                 let table_id = table.get_id();
    |                                ^^^^^ value borrowed here after move

rust borrow-checker
1个回答
0
投票
一旦您的Catalog拥有表的所有权,就可以通过引用访问它。

如果您描述的用例很常见,也许您可​​以调整add_table方法以返回对刚刚添加的表的引用。

[HashMap提供Entry API作为符合人体工程学的方法-例如,您的Entry可能看起来像这样:

add_table

现在您可以像这样使用它:

fn add_table(&mut self, table: Box<dyn Table>/*, ... other arguments */) -> &mut Box<dyn Table> { let id = // figure out id somehow // Insert table into catalog and return a reference to it self.table_id_table_map.entry(id).or_insert(table) }

© www.soinside.com 2019 - 2024. All rights reserved.