I have the following project where I want to divide some modules into subfolders.
The current file structure is simply:
src/
->main.rs
->cpu/
->cpu.rs
main.rs only contains:
fn main() {
println!("Hello, world!");
let c : cpu::Cpu;
cpu::thing();
}
and cpu/cpu.rs contains a struct declaration and a test function:
pub struct Cpu {
memory : [u8; 16],
}
pub fn thing() -> u8 {
2 // whatever, it's a test
}
How do I include the cpu.rs public functions and structs into main.rs?
No matter what I try, I get an error (could not find `cpu` in the crate root) if I use use crate::cpu::{Cpu, thing};, and using mod cpu; seems to only work on the same directory.
Searching for solutions online is extremely infuriating, since the answers are mixed up between the 2015 and 2018 rust editions, are over-complicated or are done in the same folder.
You forgot to made cpu (folder) a mod itself, you need to include a mod.rs file in the folder structure:
src/
->main.rs
->cpu/
->mod.rs
->cpu.rs
and in mod.rs reexport publicly the inner cpu module:
pub mod cpu;
Related
I think there is some redundancy in my import but I cant really figure out another way to do it
main.rs
mod lib;
use lib::calc::med_calc;
fn main() {
let mut numbers = vec![1,21,22,4,2];
med_calc(& mut numbers)
}
to me it seems weird to declare the lib.rs as a module and only then I can use the structs/functions within. Since I've already declared them as modules and public in lib.rs itself.
lib.rs
pub mod calc {
pub fn med_calc(vector: & mut Vec<u8>){
vector.sort();
println!("{}", vector[vector.len()/2])
}
}
file tree (used in cargo):
src -
|- main.rs
|- lib.rs
When you have both a lib.rs and main.rs file in your project, the lib.rs file creates a library crate that can be accessed via the crate name in your crate's binary source files (like main.rs and bin/*.rs).
For example, if the crate is named rust_tmp, then you can do:
main.rs:
use rust_tmp::calc::med_calc;
fn main() {
let mut numbers = vec![1, 21, 22, 4, 2];
med_calc(&mut numbers)
}
No need for a mod lib;. Actually, a mod lib; is counterproductive to how lib.rs is meant to be used.
I have a directory like this:
.
├── a.rs
├── b.rs
└── main.rs
main.rs:
mod a;
use a::a;
fn main() {
println!("Hello, world!");
a();
}
a.rs:
mod b;
use b::b;
pub fn a() {
b();
}
b.rs:
pub fn b() {
println!("b");
}
rustc complaints in a.rs about
file not found for module `b`
help: to create the module `b`, create file "src/a/b.rs" or "src/a/b/mod.rs"rustc(E0583)
If I put mod b; in main.rs, and replace mod b; with use crate::b::b; in a.rs, everything works well.
My question is: do I have to put every mod xxx; in the file where main() locates? I just want to call functions in the same-level rs files
When you put mod b; in a.rs, b will be considered as a submodule of module a. So, as suggested by rustc, it should be either in "src/a/b/mod.rs" or "src/a/b.rs". And when you put it instead in main.rs, it means that this module in located at the crate root, reason why it works without any problem because rustc looks for the file in the same directory as main.rs("src") and find it.
So, you don't have to put every mod xxx where main is located. If you creating an hierarchy (I mean modules and submodules and so on), you should respect the directory architecture and put mod xxx, only in the parent module, if any. You declare mod xxx in your main file for top level modules only.
You can see more explanation in the book :).
I am trying to share a struct between two files, but I am getting an error.
I have the following folder structure:
src/
Models/
Login.rs
Routes/
LoginRoute.rs
Services/
LoginService.rs
main.rs
In Login.rs I have:
#[derive(Serialize, Deserialize, Debug)]
pub struct UserLoginResponse {
id: i32,
username: String,
token: String
}
In LoginRoute.rs I have:
#[path = "../Models/Login.rs"]
pub mod Login;
#[path = "../Services/LoginService.rs"]
pub mod LoginService;
#[post("/login", format = "application/json", data = "<user>")]
pub async fn login(user: String) -> Json<Login::UserLoginResponse> {
if let Ok(sk) = LoginService::callAuthenticate(user).await {
return sk
......
In LoginService.rs I have:
#[path = "../Models/Login.rs"]
pub mod Login;
pub async fn callAuthenticate(user: String)-> Result<Json<Login::UserLoginResponse>, Error> {
...
let userLoginResponse :Login::UserLoginResponse = Login::UserLoginResponse::new(1, "admin".to_string(), api_reponse.return_result);
Ok(Json(userLoginResponse))
}
I am getting error in LoginRoute.rs on the return sk line:
expected struct 'LoginRoute::Login::UserLoginResponse', found struct 'LoginService::Login:UserLoginResponse'
Please do not use the #[path = ...] attribute for your typical organization; it should only be used in obscure cases. Each time you do mod something, you are declaring a new module. Even if two modules point to the same file due to #[path = ...], they will be distinct.
So you have multiple UserLoginResponse structs declared:
one at crate::LoginRoute::Login::UserLoginResponse
one at crate::LoginService::Login:UserLoginResponse
and maybe another if you've also declared Login in main.rs.
Since they're in distinct modules, the Rust compiler sees them as different types, which is not what you want.
Just use the idiomatic way of declaring modules. If you want to keep your existing folder structure without intermediate mod.rs files, you can declare them all in main.rs like so:
mod Models {
pub mod Login;
}
mod Routes {
pub mod LoginRoute;
}
mod Services {
pub mod LoginService;
}
And then access them elsewhere via crate::Models::Login and whatnot.
See:
How do I import from a sibling module?
You've probably already run into warnings from the compiler trying to encourage a specific style: "module [...] should have a snake case name". Idiomatic file structure would typically look like this:
src/
models/
login.rs
mod.rs
routes/
login_route.rs
mod.rs
services/
login_service.rs
mod.rs
main.rs
Where main.rs would have:
mod models;
mod routes;
mod services;
And src/models/mod.rs (for example) would have:
pub mod login;
If you have a directory structure like this:
src/main.rs
src/module1/blah.rs
src/module1/blah2.rs
src/utils/logging.rs
How do you use functions from other files?
From the Rust tutorial, it sounds like I should be able to do this:
main.rs
mod utils { pub mod logging; }
mod module1 { pub mod blah; }
fn main() {
utils::logging::trace("Logging works");
module1::blah::doit();
}
logging.rs
pub fn trace(msg: &str) {
println!(": {}\n", msg);
}
blah.rs
mod blah2;
pub fn doit() {
blah2::doit();
}
blah2.rs
mod utils { pub mod logging; }
pub fn doit() {
utils::logging::trace("Blah2 invoked");
}
However, this produces an error:
error[E0583]: file not found for module `logging`
--> src/main.rs:1:21
|
1 | mod utils { pub mod logging; }
| ^^^^^^^
|
= help: name the file either logging.rs or logging/mod.rs inside the directory "src/utils"
It appears that importing down the path, i.e. from main to module1/blah.rs works, and importing peers, i.e. blah2 from blah works, but importing from the parent scope doesn't.
If I use the magical #[path] directive, I can make this work:
blah2.rs
#[path="../utils/logging.rs"]
mod logging;
pub fn doit() {
logging::trace("Blah2 invoked");
}
Do I really have to manually use relative file paths to import something from a parent scope level? Isn't there some better way of doing this in Rust?
In Python, you use from .blah import x for the local scope, but if you want to access an absolute path you can use from project.namespace.blah import x.
I'm going to answer this question too, for anyone else who finds this and is (like me) totally confused by the difficult-to-comprehend answers.
It boils down to two things I feel are poorly explained in the tutorial:
The mod blah; syntax imports a file for the compiler. You must use this on all the files you want to compile.
As well as shared libraries, any local module that is defined can be imported into the current scope using use blah::blah;.
A typical example would be:
src/main.rs
src/one/one.rs
src/two/two.rs
In this case, you can have code in one.rs from two.rs by using use:
use two::two; // <-- Imports two::two into the local scope as 'two::'
pub fn bar() {
println!("one");
two::foo();
}
However, main.rs will have to be something like:
use one::one::bar; // <-- Use one::one::bar
mod one { pub mod one; } // <-- Awkwardly import one.rs as a file to compile.
// Notice how we have to awkwardly import two/two.rs even though we don't
// actually use it in this file; if we don't, then the compiler will never
// load it, and one/one.rs will be unable to resolve two::two.
mod two { pub mod two; }
fn main() {
bar();
}
Notice that you can use the blah/mod.rs file to somewhat alleviate the awkwardness, by placing a file like one/mod.rs, because mod x; attempts x.rs and x/mod.rs as loads.
// one/mod.rs
pub mod one.rs
You can reduce the awkward file imports at the top of main.rs to:
use one::one::bar;
mod one; // <-- Loads one/mod.rs, which loads one/one.rs.
mod two; // <-- This is still awkward since we don't two, but unavoidable.
fn main() {
bar();
}
There's an example project doing this on Github.
It's worth noting that modules are independent of the files the code blocks are contained in; although it would appear the only way to load a file blah.rs is to create a module called blah, you can use the #[path] to get around this, if you need to for some reason. Unfortunately, it doesn't appear to support wildcards, aggregating functions from multiple files into a top-level module is rather tedious.
I'm assuming you want to declare utils and utils::logging at the top level, and just wish to call functions from them inside module1::blah::blah2. The declaration of a module is done with mod, which inserts it into the AST and defines its canonical foo::bar::baz-style path, and normal interactions with a module (away from the declaration) are done with use.
// main.rs
mod utils {
pub mod logging { // could be placed in utils/logging.rs
pub fn trace(msg: &str) {
println!(": {}\n", msg);
}
}
}
mod module1 {
pub mod blah { // in module1/blah.rs
mod blah2 { // in module1/blah2.rs
// *** this line is the key, to bring utils into scope ***
use crate::utils;
pub fn doit() {
utils::logging::trace("Blah2 invoked");
}
}
pub fn doit() {
blah2::doit();
}
}
}
fn main() {
utils::logging::trace("Logging works");
module1::blah::doit();
}
The only change I made was the use crate::utils; line in blah2 (in Rust 2015 you could also use use utils or use ::utils). Also see the second half of this answer for more details on how use works. The relevant section of The Rust Programming Language is a reasonable reference too, in particular these two subsections:
Separating Modules into Different Files
Bringing Paths into Scope with the use Keyword
Also, notice that I write it all inline, placing the contents of foo/bar.rs in mod foo { mod bar { <contents> } } directly, changing this to mod foo { mod bar; } with the relevant file available should be identical.
(By the way, println(": {}\n", msg) prints two new lines; println! includes one already (the ln is "line"), either print!(": {}\n", msg) or println!(": {}", msg) print only one.)
It's not idiomatic to get the exact structure you want, you have to make one change to the location of blah2.rs:
src
├── main.rs
├── module1
│ ├── blah
│ │ └── blah2.rs
│ └── blah.rs
└── utils
└── logging.rs
main.rs
mod utils {
pub mod logging;
}
mod module1 {
pub mod blah;
}
fn main() {
utils::logging::trace("Logging works");
module1::blah::doit();
}
utils/logging.rs
pub fn trace(msg: &str) {
println!(": {}\n", msg);
}
module1/blah.rs
mod blah2;
pub fn doit() {
blah2::doit();
}
module1/blah/blah2.rs (the only file that requires any changes)
// this is the only change
// Rust 2015
// use utils;
// Rust 2018
use crate::utils;
pub fn doit() {
utils::logging::trace("Blah2 invoked");
}
I realize this is a very old post and probably wasn't using 2018. However, this can still be really tricky and I wanted to help those out that were looking.
Because Pictures are worth a thousand words I made this simple for code splitting.
Then as you probably guessed they all have an empty pub fn some_function().
We can further expand on this via the changes to main
The additional changes to nested_mod
Let's now go back and answer the question:
We added blah1 and blah2 to the mod_1
We added a utils with another mod logging inside it that calls some fn's.
Our mod_1/mod.rs now contains:
pub mod blah.rs
pub mod blah2.rs
We created a utils/mod.rs used in main containing:
pub mod logging
Then a directory called logging/with another mod.rs where we can put fns in logging to import.
Source also here https://github.com/DavidWhit/Rust_Modules
Also Check Chapters 7 for libs example and 14.3 that further expands splitting with workspaces in the Rust Book. Good Luck!
Answers here were unclear for me so I will put my two cents for future Rustaceans.
All you need to do is to declare all files via mod in src/main.rs (and fn main of course).
// src/main.rs
mod module1 {
pub mod blah;
pub mod blah2;
}
mod utils {
pub mod logging;
}
fn main () {
module1::blah::doit();
}
Make everything public with pub you need to use externally (copy-pasted original src/utils/logging.rs). And then simply use declared modules via crate::.
// src/module1/blah.rs
use crate::utils::logging;
// or `use crate::utils` and `utils::logging::("log")`, however you like
pub fn doit() {
logging::trace("Logging works");
}
p.s. I shuffled functions a bit for a cleaner answer.
If you create a file called mod.rs, rustc will look at it when importing a module. I would suggest that you create the file src/utils/mod.rs, and make its contents look something like this:
pub mod logging;
Then, in main.rs, add a statement like this:
use utils::logging;
and call it with
logging::trace(...);
or you could do
use utils::logging::trace;
...
trace(...);
Basically, declare your module in the mod.rs file, and use it in your source files.
I have a little project and I want to encapsulate a struct's fields and use implemented methods.
├── src
├── main.rs
├── predator
└── prey
├── cycle.rs
└── mod.rs
cycle.rs
struct Prey {
name: String,
}
impl Prey {
pub fn new(n: String) -> Prey {
Prey { name: n }
}
pub fn get_name(&self) -> &str {
self.name.as_str()
}
}
I'd like to leave Prey as private.
main.rs
use prey::cycle::Prey;
mod prey;
fn main() {
let pr = Prey::new("Hamster".to_string());
println!("Hello, world! {}", pr.get_name());
}
I get an error:
error: struct `Prey` is private
I know that if I put pub before struct Prey {}, I'll get the expected result. I will be grateful for an explanation, how, why not and/or best practices.
Visibility works at the module level. If you want module X to have access to an item in module Y, module Y must make it public.
Modules are items too. If you don't make a module public, then it's internal to your crate. Therefore, you shouldn't worry about making items in that module public; only your crate will have access to it.
The crate root (usually the file named lib.rs or main.rs) is the root module of your crate. It defines the public interface of the crate, i.e. public items in the crate root are accessible from other crates.
In your example, you write mod prey;. That defines the prey module as private, so items in the prey module are not accessible from other crates (unless you reexport them with pub use). That means you should make prey::cycle::Prey public.