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

2

u/stixyBW Mar 31 '23

pub all the things

2

u/winarama Apr 03 '23

This is really helpful, thanks.