1

This is actually a two part question:

  1. Can I have a single module in separate files in Rust?

enter image description here

This is my file layout. Is it possible to have a single logging module and have a set of structs/traits to be defined inside this module, but in separate physical files(logger,sql)?

If it's possible, can such project be built with current Cargo?

And, if it is possible, how do I reference my structs, defined in logging module, in my app.rs?

I'm using: rustc 0.12.0-pre-nightly (cf1381c1d 2014-07-26 00:46:16 +0000)

Valentin V
  • 24,971
  • 33
  • 103
  • 152
  • Yes, by splitting a module into sub-modules and hiding that fact in the API. This is already answered: http://stackoverflow.com/questions/22596920/rust-splitting-a-single-module-across-several-files – BurntSushi5 Jul 29 '14 at 17:02

1 Answers1

14

Strictly speaking, you cannot have one module split over different files, but you don't need to as you can define child modules to similar effect (which is also a better solution).

You could arrange your modules like this:

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

And here's how the files could look like

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/logging/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/logging/logger.rs

pub struct Logger;

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

src/logging/sql.rs

pub struct Sql;

pub trait SqlTrait {
    fn sql(&mut self, &str);
}
A.B.
  • 15,364
  • 3
  • 61
  • 64
  • 2
    Actually, you can split a single module over several files, with include!("path to your other file"). However, it's _greatly_ recommended that you do as A.B. says, and split them into separate modules, and re-export them with pub use. – moveaway00 Jul 29 '14 at 17:25
  • Since the introduction of hygiene for `include!`, it is for all practical purposes useless now and should never be used. – Chris Morgan Jul 29 '14 at 22:07