prnvbn
prnvbn

Reputation: 1027

How to import a function from another folder in the folder above

My directory structure looks like this

src
├── main.rs
├── paas_core
│   ├── create.rs
│   └── mod.rs
└── rest_api
    ├── mod.rs
    └── rest.rs

I want to use a function declared in file create.rs in the file called rest.rs. I am trying to use the module in the rest_api module but I can not figure out how to do it.

I tried using super::paas_core in rest.rs but that didn't work.

Upvotes: 4

Views: 2674

Answers (1)

Benjamin Boortz
Benjamin Boortz

Reputation: 186

In the file rest_api/rest.rs do you have to use use crate::paas_core; in order to be able to reference from rest_api to paas_core and paas_core/mod.rs need the statement pub mod create; to ensure you can call the function from rest_api directly using paas_core::create::create_func();

I hope it explains it. An full example might look like this:

file: main.rs

mod paas_core;
mod rest_api;

fn main() {
    rest_api::rest_func();
}

file: rest_api/mod.rs


mod rest;

pub fn rest_func() {
    println!("rest_func() in rest_api/mod.rs called!");
    rest::rest_caller();
}

file: rest_api/rest.rs

use crate::paas_core;
pub fn rest_caller() {
    println!("rest_caller() in rest_api/rest.rs called!");
    paas_core::create::create_func();
}

file: paas_core/mod.rs

pub mod create;

file: paas_core/create.rs

pub fn create_func() {
    println!("create_func() in paas_core/create.rs finally called!");
}

output if you are running it:

rest_func() in rest_api/mod.rs called!
rest_caller() in rest_api/rest.rs called!
create_func() in paas_core/create.rs finally called!

Upvotes: 8

Related Questions