Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a file from another that is not main.rs nor lib.rs

Tags:

module

rust

(I'm a Rust beginner) I have three files : main.rs, board.rs and case.rs. I want to include case.rs into board.rs, and board.rs into main.rs, so the board uses the case, and we can access the board in main.

I've successfully added the board into main, but the way I did doesn't seem to work for the second part.

I've tried to encapsulate every file's content into "mod {}" but it doesn't change the problem. Also I tried every combinations of "mod" and "use".

Every file is in the folder src/, and I'd like them not to move from there if possible.

main.rs

mod board;

fn main() {
    let mut b: Board = Board::new();
}

board.rs

mod case;

pub struct Board {
    board: [ Case; 9 ]
}

// There is also the impl part of course, let's keep it short

case.rs

pub enum Case { Empty, Full(Player) }

Using VSCode with the Rust plugin, the "case" word on the first line of the board.rs file is underlined red, and it says :

"src/case.rs file not found for module case help: name the file either board\case.rs or board\case\mod.rs inside the directory "src""

Why doesn't it search in the current directory?

like image 985
Xobtah Avatar asked Jun 22 '19 10:06

Xobtah


1 Answers

Your files could look like as follows:

case.rs:

#[derive(Clone, Copy, Debug)]
struct Player;

#[derive(Clone, Copy, Debug)]
pub enum Case {
    Empty,
    Full(Player)
}

board.rs:

use crate::case::Case;

#[derive(Debug)]
pub struct Board {
    board: [ Case; 9 ]
}

impl Board {
    pub fn new() -> Self {
        Self { board: [Case::Empty; 9] }
    }
}

main.rs:

mod case;
mod board;

use crate::board::Board;

fn main() {
    println!("{:?}", Board::new());
}

Basically you create a crate (a binary one, because of your main.rs) and that crate can have modules. A module can be a file, or it can be a folder as well (if it happens to have a mod.rs). (And for the sake of completeness, it could also be an inline module without direct relation to the file system.)

Your mod statements (the ones which are indicating files and folders, not the ones which you use to create inline modules) should either be placed at the top level of your crate (e.g. in your main.rs or lib.rs) or at the module levels (in your mod.rs files) depending on the desired structure.

For further info on this, please read the The Rust Programming Language book's relevant chapter: Packages and Crates.

like image 66
Peter Varo Avatar answered Oct 31 '22 02:10

Peter Varo