How to include a file in two files (including main) in rust and directly use its namespace name in both files?

Viewed 55

I have this structure:

src
|   main.rs
|   fcfs.rs
|   proc.rs

I want to include proc.rs in both main.rs and fcfs.rs. Initially, I used mod proc in both files. This only worked in main.rs, and it did not work in fcfs.rs

Consulting SO, I found an answer in which the path attribute was described.

so I have the three files as follows:

// proc.rs
#[derive(Debug, Clone)]
pub struct Proc {
    name: String,
    cpu_burst: u32, 
    priority: u32,
    time_rem: u32,
}

impl Proc {
    pub fn new(name: String,
        cpu_burst: u32,
        priority: u32,
        time_rem: u32) -> Proc {
        Proc {
            name, 
            cpu_burst,
            priority,
            time_rem,
        }
    }
}
// fcfs.rs
#![allow(dead_code)]

#[path = "./proc.rs"] mod proc;
use proc::*;

pub struct FCFSScheduler {
    procs: Vec<Proc>,
}

impl FCFSScheduler {
    pub fn new() -> FCFSScheduler {
        FCFSScheduler {
            procs: Vec::<Proc>::new()
        }
    }

    pub fn add(&mut self, t: proc::Proc) {
        self.procs.push(t);
    }
}
// main.rs
#![allow(dead_code)]

mod proc;
mod fcfs;

use proc::*;
use fcfs::*;

fn main() {
    let t = Proc::new(String::from("T1"), 1, 1, 1);
    let mut s = FCFSScheduler::new(); 
    s.add(t);
}

The problem with me is with the s.add(t) line in main.rs.

I get the following problem.

error[E0308]: mismatched types
  --> src\main.rs:12:11
   |
12 |     s.add(t);
   |           ^ expected struct `fcfs::proc::Proc`, found struct `proc::Proc`

This is solved by changing t to a fcfs::proc::Proc, but I want to know about the better way to manage imports because this does not sound scalable at all. How can I simply include proc.rs and just use proc::Proc everywhere?

1 Answers

Using #[path = ..] like this will make Rust think that proc.rs is two separate modules instead of one, which is why you get the confusing "expected Proc, found Proc" error message.

Keep the module defined in main.rs:

mod proc;

And you can access the module via its path in fcfs.rs like so:

use crate::proc::*;

See also:

Related