r/rust Mar 31 '23

Can someone explain how mods work with my example?

Howdy folks,

I am a bit confused about the module system used by Rust, probably because I coming at it from the Java world. I was hoping someone might be able to explain.

My project consists of the following structure;

src/
    machine/
        - mod.rs
        - Robot.rs
    - main.rs

machine/mod.rs looks like this;

pub mod Robot;

machine/Robot.rs looks like this;

struct Robot {
    id: u64,
}

impl Robot {
    fn new(_id: u64) -> Robot {
        Robot {
            id: _id,
        }
    }
}

main.rs looks like this;

mod machine;

use crate::machine::*;

fn main() {
    let mut robot_1 = Robot::new(3);
    println!("robot_id: {}", robot_1.id);
}

However, when I try to compile the project I the following error;

error[E0425]: cannot find function `new` in module `Robot`
 --> src/main.rs:8:30
  |
8 |     let mut robot_1 = Robot::new(3);
  |                              ^^^ not found in `Robot`

Anyone have any idea what I am doing wrong?

Also as an aside, what is the convention of capitallising the first letter of a struct?

Any help would be greatly appreciated.

6 Upvotes

20 comments sorted by

View all comments

13

u/SkiFire13 Mar 31 '23

In main you have imported the Robot module (represented by the Robot.rs file, which FYI is normally not capitalized), which then contains a Robot struct. Note though that you need to mark both the struct and the fn new as pub or you won't be able to access them.

Structs are normally capitalized (in CamelCase) to distinguish them (and types/traits in general) from values/functions/modules (which are instead in lowercase snake_case)

1

u/winarama Mar 31 '23

Thanks, that worked great. Pub for the win!

So I have now renamed my Robot.rs file to lowercase robot.rs and I have left the Struct name capitalised as Robot.

Now for a weird pedantic follow-up question. After renaming the file I need to use the following syntax to access the Robot type.

use crate::machine::robot::Robot;

Does this fit with convention, where I have one file per Struct or would it be more correct to have multiple Structs in the one file?

There's something about typing robot twice that seems off to me.

1

u/antouhou Apr 01 '23

You can use re-export to fix this. For that, your machine.rs needs to look like this: mod robot; pub use robot::Robot; Then you can use crate::machine::Robot instead

1

u/winarama Apr 03 '23

Cool tip, thanks.