How to organise file structure of my project?

Hi everyone,
I have a question about file structure of rust. I have a JAVA project with following file structure(tree)

javaTemplate
-classA.java
-classB.java
-MainClass.java

Where each class has the following structure
ClassA.java

package javaTemplate;

public class ClassA {
	public static int temp = 5;
}

ClassB.java

package javaTemplate;

public class ClassB {
	
	public void ClassB() {
		
	}
	
	public void saySomething() {
		System.out.println("The value of static int in ClassA is: " + ClassA.temp);
	}
}

MainClass.java

package javaTemplate;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassB classBobj = new ClassB();
		classBobj.saySomething();
	}
}

This is working just fine. When I want to try the same thing with similar file structure in rust, it doesn't work. I have tried something like following in playground.

mod class_a{
    pub static TEMP: i32 = 5;
}

mod class_b{
    mod class_a;
    
    pub fn say_something(){
        println!("The value of static int in ClassA is:  {}", class_a::TEMP);
    }
}


fn main() {
    class_b::say_something();    

}

This will give me an error as follows.

file not found for module `class_a`
 --> src/main.rs:6:5
  |
6 |     mod class_a;
  |     ^^^^^^^^^^^^
  |
  = help: to create the module `class_a`, create file "src/class_b/class_a.rs" or "src/class_b/class_a/mod.rs"

error[E0425]: cannot find value `TEMP` in module `class_a`
 --> src/main.rs:9:72

I am aware that if I put mod class_a inside class_b it will work. But then, the file structure will be changed. What am I asking is, is there anyway to make it working ?

Multiple uses of mod … in Rust result in multiple different modules being defined. You might be looking for use … instead.

mod class_a {
    pub static TEMP: i32 = 5;
}

mod class_b {
    use crate::class_a;

    pub fn say_something() {
        println!("The value of static int in ClassA is: {}", class_a::TEMP);
    }
}

fn main() {
    class_b::say_something();
}

If you want separate files, then you do

main.rs

mod class_a;
mod class_b;

fn main() {
    class_b::say_something();
}

class_a.rs

pub static TEMP: i32 = 5;

class_b.rs

use crate::class_a;

pub fn say_something() {
    println!("The value of static int in ClassA is: {}", class_a::TEMP);
}

(btw, note that this say_something function is more akin to a static method in Java)

Also, for an immutable value like TEMP above, it might be more idiomatic to use a const instead of a static; and you might want to make the modules public, too, writing pub mod class_a { … } or pub mod class_a;.

1 Like