Dragonborn
Dragonborn

Reputation: 1815

Why do I need mod keyword for accessing structs in file at same level for Rust?

mod pair;
mod point;
mod rectangle;

use pair::Pair;
use point::Point;
use rectangle::Rectangle;

Shouldn't these structs be available in the same scope for code files at same level as pair.rs, point.rs and rectangle.rs?

And is there python like syntax?

from A import B

Upvotes: 3

Views: 1354

Answers (1)

JayJamesJay
JayJamesJay

Reputation: 623

Rust's module system allows you to split code into small, reusable modules. You declare new module using mod keyword. Every module has its own scope. It means that if you want to use struct (or anything else) from module, you need to type module_name::StructName or bring it into your code's scope using use keyword (use module_name::StructName). This is because there might be two different structs with the same name in two different modules. E.x. There is a struct A in module b, and there is struct A in module C. If there wasn't separate scope for each module, which struct A would be imported? Rust wouldn't be able to figure out what was our intention. It may cause bugs and other issues.

To import module you need to use module's name double colon and name of the imported submodule or struct e.x.

use std::io;

To import all submodules of one module you need to use module's name double colon and star sign, e.x.

use std::*;

You can also refer to parent module using super keyword and import all its modules at once, e.x.:

mod pair;
mod point;
mod rectangle;

use super::*;

Since Rust 1.25 you can nest import groups, e.x.:

use std::{
    cmp::{self, Ordering}, 
    fs, 
    io::prelude::*,
};

Please also read:

Upvotes: 1

Related Questions