首页 文章

是否可以在Rust中的不同源文件中使用模块

提问于
浏览
1

这实际上是一个两部分问题:

  • 我可以在Rust的单独文件中使用单个模块吗?

enter image description here

这是我的文件布局 . 是否可以使用单个 logging 模块并在此模块中定义一组结构/特征,但是在单独的物理文件(logger,sql)中?

如果可能的话,这样的项目可以用当前货物建造吗?

并且,如果可能,我如何在我的应用程序中引用 logging 模块中定义的结构?

我正在使用:rustc 0.12.0-每晚(cf1381c1d 2014-07-26 00:46:16 0000)

1 回答

  • 10

    严格地说,您不能将一个模块拆分为不同的文件,但您不需要将子模块定义为类似的效果(这也是一个更好的解决方案) .

    你可以这样安排你的模块:

    src/app.rs
    src/logging/mod.rs // parent modules go into their own folder
    src/logging/logger.rs // child modules can stay with their parent
    src/logging/sql.rs
    

    以下是文件的外观

    SRC / app.rs

    mod logging;
    
    pub struct App;
    
    fn main() {
        let a = logging::Logger; // Ok
        let b = logging::Sql; // Error: didn't re-export Sql
    }
    

    SRC /记录/ mod.rs

    // `pub use ` re-exports these names
    //  This allows app.rs or other modules to import them.
    pub use self::logger::{Logger, LoggerTrait};
    use self::sql::{Sql, SqlTrait};
    use super::App; // imports App from the parent.
    
    mod logger;
    mod sql;
    
    fn test() {
        let a = Logger; // Ok
        let b = Sql; // Ok
    }
    
    struct Foo;
    
    // Ok
    impl SqlTrait for Foo {
        fn sql(&mut self, what: &str) {}
    }
    

    SRC /记录/ logger.rs

    pub struct Logger;
    
    pub trait LoggerTrait {
        fn log(&mut self, &str);
    }
    

    SRC /记录/ sql.rs

    pub struct Sql;
    
    pub trait SqlTrait {
        fn sql(&mut self, &str);
    }
    

相关问题