Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

How to avoid redundant module naming for Single struct modules in rust?

Maybe this just bothers me, but in certain cases I'd like to have one struct per module file.

Let's say I have a struct named User like this:

struct User {
    name: String
}

And let's say I have a file structure like where the User struct code is located in src/models/user.rs like this:

src/
    models/
           user.rs

And now I'd like to be able to use the User struct like this:

use crate::models::User;

Of course that's not possible. Instead it needs to be referred with:

use crate::models::user::User;

To me this looks quite ugly and I consider it redundant if both words, user and User, are part of the module path.

Is there any solution that doesn't seem to be as "clumsy" as the one just described?

It might as well be the case that I missed something regarding how the rust module naming system works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can re-export the User struct in the models module with pub use user::User; and optionally make the user submodule private (so that no one outside of models can access it). Externally, the User struct can then be referred to as a member of the models module with crate::models::User.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share

1.2m questions

2.1m answers

5 comments

56.5k users

...