Rust pass box reference without move


I'm writing a RDBMS in rust

The db.catalog maintain a hashmap from table_id to table:

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

And when I add a boxed table to the catalog, move occurred. Then I can't use table instance anymore:

// 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();

compile error:

error[E0382]: borrow of moved value: `table`
   --> src/
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

Box by definition exists in one place only. If you want an owned trait object to be usable from more than one location, you have to use Arc<dyn Table>.

Alternatively, you could search for that object in the HashMap (or use Entry API when inserting), and get a temporary access to &dyn Table this way.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.