1
votes

I want to create the following datamodell in rust.

Uml diagramm of the datamodell

In other languages it is normal to create one file for each struct. I created the following file structure:

.
│
┝ data_model
│   │
│   ┝ mod.rs
│   ┝ house.rs
│   └ garage.rs
│
└ main.rs

I need a list of houses in my garage struct and a list of garages in my house struct. But I can't include this files. I tried it like that:

main.rs:

mod data_model;
...

mod.rs:

mod house;
mod garage;

That works fine. I am able to use the structs inside the main file.

But if I do this one (mod.rs and main.rs didn't changed):

garage.rs:

mod house;

struct garage{
    houses: Vec<house>
}

it wouldn't work, because rust searches for the file data_model/garage/house.rs instead of only searching for data_model/house.rs.

But I don't want to move house.rs to garage/house.rs because this would look like, the house is a component of the grage. Also it wouldn't work, because I also have to include the grage into the house and that won't work, if the house is component of the grage.

Whats the right way to create a datamodel like this?

PS: I know, that there are some problems because I don't use pointers to refer from house to garage and from garage to house. But that is not the problem so far.

1
Creating recursive structures in Rust is very difficult, is this what you really want?Daniel Fath
"In other languages it is normal to create one file for each struct." but not in Rust, where each file creates a module, and modules are usually made to contain things that relate to each other.mcarton

1 Answers

2
votes

mod house; in garage.rs does not work because house in not a submodule of garage.

What you really want is to user super::house; in garage.rs.

Note however that creating one file per type is not idiomatic in Rust, and you shouldn't try to blindly follow other language's idioms when learning a new language. Having one file per type is possible, but not worth the effort. It is more common to group types in a module and to split files in a logical way, with things that work together in the same file. You are also not following Rust's naming conventions (eg. types should be CamelCase).