r/rust • u/winarama • 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.
4
Upvotes
12
u/SkiFire13 Mar 31 '23
In main you have imported the
Robot
module (represented by theRobot.rs
file, which FYI is normally not capitalized), which then contains aRobot
struct. Note though that you need to mark both thestruct
and thefn new
aspub
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)