How do you group set of conceptually similar, but different as type, types

Hello everyone,

I have a set of database interface objects that are different as type and has different methods.
But, they are conceptually belong to a group called database interfaces.

I like to initialize them all at once & access them through one interface.
In JavaScript, I would do the following:

class UsersInterface { storeUser() {}, ... }
class PostsInterface { storePost() {}, ... }
const databaseInterfaces = new Map();
databaseInterfaces.set('Users', new UsersInterface());
databaseInterfaces.set('Posts', new PostsInterface());
const usersInterface = databaseInterfaces.get('Users');

Is same or of the sorts possible with Rust?
I tried with HashMap, Box & Trait combination. But, only the methods in trait are accessible. In my case, although all the db interface objects will have a few generic lifecycle methods, each of the will have their own set of methods.
Then I tried with Enums. There also I get similar error:

println!("{} from A", collection_a.store_a());
   |                             ^^^^^^^ method not found in `Option<&DBInterfaces>`

Could someone point me in the right direction?

Good day!

I’m confused why you aren’t just using a struct here. Like:

struct DatabaseInterfaces {
    users: UsersInterface,
    posts: PostsInterface,

But if you really do need an enum-based solution, you have to match on it. For example:

let users_interface = match &database_interfaces["Users"] {
    DbInterface::Users(interface) => interface,
    _ => panic!("wrong interface stored under `Users` key"),

Yeah, why am I not? I will do that. Enum approach is not as clean as struct approach anyway.


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.