Question

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)

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top