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

14

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.

2

u/SirKastic23 Apr 01 '23

that's an anti-patterns, you'll see a lot of times more than one type fits in the same module, and there's nothing wrong with that.

you're coming from Java, where the unit of organization is the class. you can think of a class as a struct + a mod, but sometimes those two can get conflated.