How do I import structs from a file ""

Still new here, and my second day with Rust. Sorry for the low beginner question.
How do I import structs so that my file is not too messy?

and is this a recommended way of organizing structs?

pub struct A {}

use ?::A::??

In this respect Rust works differently than other languages, because in Rust you don't directly import things from files. Files aren't usable by themselves. You define modules, which may be sourced from a file, and then you can import names from the modules.

The difference is subtle, but important to understand mod and use. Definition of modules with mod works just like definition of struct or fn, it creates a new named item in its scope:

mod structs;

If you put it at the root of the crate (in this will make crate::structs exist, and create::structs::A will refer to the struct in it.

To avoid writing crate::structs::A, you can import the name with use crate::structs::A;

Do I have to make all fields public within a struct then?
It's pretty cumbersome

pub struct A{
    pub x: HashMap<String, X>,
    pub y: HashMap<String, Y>,

Only if you want to directly access the fields from outside the module.

In addition to what Alice said. You generally wouldn't have modules like functions or structs, having modules like that in any languages isn't so much an anti-pattern as it is a beginner's pattern. You generally define your types where you use them with their associated functions.

1 Like

coming from a dynamic language, it felt better hiding them somewhere else. But your answer makes sense to me.

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.