January 2019
Beginner to intermediate
554 pages
13h 31m
English
Modules can also be created as files. For instance, for a main.rs file in a directory named foo, we can create a module bar as a file in the same directory as foo/bar.rs. Then in main.rs, we need to tell the compiler of this module, that is, declare the module with mod foo;. This is an extra step when using file-based modules. To demonstrate using a file as a module, we have created a directory named modules_demo, which has the following structure:
+ modules_demo└── foo.rs└── main.rs
Our foo.rs contains a struct Bar, with its impl block:
// modules_demo/foo.rspub struct Bar;impl Bar { pub fn init() { println!("Bar type initialized"); }}
We want to use this module in main.rs. Our main.rs, has the following code:
// modules_demo/main.rs ...
Read now
Unlock full access