Using Rust traits within module that is declared in library root of project

Viewed 402

I'm building a tool in Rust that is able to generate dummy time series data for testing different systems we have in place. I am trying to implement a trait called 'Batch' that is declared within my lib.rs which is in the root of the project. However, within my modules Rust is complaining this trait is not in scope, how can I access declarations on a higher namespace from within my modules?

This is how my project looks like:

 - main.rs
 - lib.rs
 - factory
     - cassandra.rs
     - jboss.rs
     - mod.rs
 - drain
    - http.rs
    - cqlsh.rs
    - mod.rs

lib.rs contains:

pub trait Batch<T> {
  fn create(&self) -> Option<T>
}

And within cassandra.rs and jboss.rs I have structs for which I am trying to implement Batch. Within lib.rs I've declared both modules using:

pub mod drains;
pub mod factory;

Is this even the right approach or should I just combine cassandra.rs & jboss.rs in one file and declare the trait there?

1 Answers

The items from other modules are not visible by default, even if this other module is the parent of current one. You must explicitly use them.

For such cases, there are two ways to do it conveniently:

  • use crate::Batch, if you want to keep this trait in the root;
  • use super::Batch, if you want to be able to move the whole hierarchy (with trait and its implementrations) somewhere else.
Related