Omegon
Omegon

Reputation: 461

How do I import a file from a folder in main?

I have such a directory structure:

structs
    -book.rs
main.rs

I just read about modules and am trying to import a structure from book.rs in main:

book.rs

#[derive(Debug)]
pub struct book{
    pub title:u32
}

main.rs

mod book;

fn main() {
   print!("start")
}

And this causes an error: unresolved module, can't find module file: book.rs , or book/mod.rs

I tried in different ways, but it doesn't work out. I will be glad of help to understand what the error is.

Upvotes: 1

Views: 255

Answers (1)

Samathingamajig
Samathingamajig

Reputation: 13245

You need to make structs a module to be able to import things.

structs
    -book.rs
    -mod.rs
main.rs

main.rs

mod structs;
use crate::structs::book::book;

fn main() {
    let b = book {
        title: "The Rust Programming Language".to_string(),
    };
    print!("{:?}", b);
}

structs/mod.rs

pub mod book;

structs/book.rs

#[derive(Debug)]
pub struct book{
    pub title: String,
}

You should also change book to be Book when you define the struct since structs should be in PascalCase not camelCase or snake_case

Upvotes: 3

Related Questions