How to use functions from one file among multiple files?

后端 未结 1 1828
旧巷少年郎
旧巷少年郎 2020-12-22 04:08

I\'m trying to use the functions from one file with multiple other files.

When I try adding \'mod somefile\' to the files, the Rust compiler wants them to be nested

1条回答
  •  生来不讨喜
    2020-12-22 04:22

    You need mod zzz; only once in the main.rs.

    In aaa.rs and bbb.rs you need a use crate::zzz;, not a mod zzz;.

    An example:

    File src/aaa.rs:

    use crate::zzz; // `crate::` is required since 2018 edition
    
    pub fn do_something() {
        zzz::do_stuff();
    }
    

    File src/bbb.rs:

    use crate::zzz;
    
    pub fn do_something_else() {
        zzz::do_stuff();
    }
    

    File src/main.rs:

    // src/main.rs
    mod aaa;
    mod bbb;
    mod zzz;
    
    fn main() {
        aaa::do_something();
        bbb::do_something_else();
    }
    

    File src/zzz.rs:

    pub fn do_stuff() {
        println!("does stuff zzz");
    }
    

    You would need a mod zzz; inside of aaa module only if you had a directory called aaa and inside of it a files mod.rs and zzz.rs. Then you would have to put mod zzz; in mod.rs to make the submodule aaa::zzz visible to the rest of your program.

    0 讨论(0)
提交回复
热议问题