Different files same namespace


#1

Hey,

I am a bit confused by the namespacing in rust.
If I use a structure like this everything works fine:

main.rs

mod controller;
use controller::Controller;

fn main() {
  let jc = controller::job::Job::new();
  jc.register(...);
}

controller/mod.rs

pub mod job;
pub trait Controller {...};

controller/job.rs

use controller::Controller;
pub struct Job {...};
impl Job {
  pub fn new() -> Job { Job; }
}
impl Controller for Job {
  fn register(...) -> ...;
}

But how could I access Job in main.rs like this, but keeping Job and Controller in different files?

main.rs

mod controller;
use controller::Controller;

fn main() {
  let jc = controller::Job::new();
  jc.register(...);
}

#2

Given that Job is in controller::job, you should be able to add

use controller::job::Job;

into main.rs, which lets you

let jc = Job::new();

Which is generally more idiomatic. (also, four spaces) If you really want controller::Job::new(); then you need to:

use Job inside of controller:

// in controller/mod.rs
pub use job::Job;

// in main.rs
use controller;

Does that make sense?


#3

Yes it works with pub use like I wanted it to.
(The two spaces are only because of the rapid example typing ;))

Hmm… I understand that using controller::job::Job is more idiomatic, but I would like to keep the developer in mind that Job is of kind controller. So that I don’t have to name it JobController.


#4

Sure! Rules are made to be broken. Especially if you might have more than one Job in scope. It’s “prefer this, not that”, not “always, 100% do this.”

:+1: