A confused problem about multi-file

I meet a confused problem

|-- src |
        |--main.rs
        |--alg.rs
        |--material.rs

I want to refer to some struct in alg.rs from material.rs

// src/material.rs: 
...
mod alg;
use crate::alg::*;

but failed

error[E0432]: unresolved import `crate::alg`
   --> src\material.rs:144:16
    |
144 |     use crate::alg::*;
    |                ^^^ maybe a missing crate `alg`?

May I refer to struct in others rs only in main.rs/lib.rs?
I am a newbie, please help, thanks.

For every file in the directory tree, you need to have a corresponding mod <file>;
You're probably missing a mod alg; in main.rs.

When discovering which files are in your crate, rustc will read main.rs and look for any mod foo statements. If it finds one, it'll add foo.rs or foo/mod.rs to the crate.

I'm guessing your main.rs didn't declare that alg.rs is part of the crate.

// main.rs

mod alg;   // <----

use crate::alg::*;
1 Like

thanks @ArifRoktim and @Michael-F-Bryan reply.
I have added mod alg in code, still failed.
I am not that refer to struct in alg.rs in main.rs, but in materail.rs.
I can refer to struct in alg.rs in main.rs, but failed in material.rs.

What is the new error message? Or is it the same error message?

error[E0583]: file not found for module `alg`
   --> src\material.rs:144:5
    |
144 |     mod alg;
    |     ^^^^^^^^
    |
    = help: to create the module `alg`, create file "src\material\learning\alg.rs"

error[E0432]: unresolved import `crate::alg`
   --> src\material.rs:145:16
    |
145 |     use crate::alg::*;
    |                ^^^ maybe a missing crate `alg`?

I have tried to other different writing, but still failed.

What's the message when you remove the mod alg; from material.rs and put it in main.rs instead?

I tried testing it out myself. I have:

main.rs

mod material;
mod alg;

fn main() {
    println!("Hello, world!");
}

alg.rs

struct Foo;

material.rs

use crate::alg::*;

And it compiles fine.

1 Like

It works, thank you

1 Like