Peter Ludvigsen
Peter Ludvigsen

Reputation: 350

Structuring of data in Rust

I'm trying to convert an old personal Java project into Rust as a learning experience. The basic data structure looked like this:

In the Java program I took a decision that there should never exist more than one object for each book ("The Hobbit") in the program. If a new book (maybe through user input) entered the system the first thing I would do was to test if it was already in the Library, and then replace the user input with the book-object from the Library. This vastly simplified a lot of logic since you could always count on comparing books by reference was valid.

Anyway, I am now rewriting this code in Rust and I have run into a problem regarding organizing my data in memory.

Having a Library with a collection of Authors is straight forward. However, how do I organize my books?

In Java the Library contained a HashMap with all the books which made it possible to find a book in constant time. Each Author also has a list of books (ordered by date) which made it possible to list all the books by an author.

However, unless I'm mistaken, a Vec in Rust can't contain references to structures. So, to me it looks like it is not possible to for each Author to have a vector of references to the books in the Library.

How should I do this? Is it possible to keep this structure without having multiple copies of the same Book structure? I would really like to be able to say Library.get_book(id).set_title("New title") and then have the title changed in the entire program.

Upvotes: 0

Views: 254

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 300349

Given that your code sample already features IDs, the solution can be straightforward:

  • the Library will have a hash-map or BTree mapping an BookId to its Book
  • all other structures that reference a book do so by having a copy of its BookId

And of course you would do the same with AuthorId and Author.

Another possibility is to use Rc and Weak, however unless carefully managed you may get memory leaks.

Upvotes: 2

Related Questions