How to call a namespace in a module?


#1

Hello everyone,

I was wondering, how can we call a namespace in a module ? Indeed, I’d like to use std::process::exit(0) in order to cleanly exit the program inside a module function.
But when I write use std::process before pub mod sthing, the compiler tells me that process::exit(0) isn’t valid.

Kind regards


#2

Hi

Can you paste some code?


#3

Names are relative from the current module by default. std is only brought into scope at the root. This means you have two options:

  1. Bring std into scope.'use std::process; and then process::exit(0). This is the standard style.
  2. Use :: to make the name start from the root. ::std::process::exit.

#4

Thanks for your answers guys !

Ok, so I tried this :

use std::process;

my_mod.rs

pub my_mod{
       pub fn test(){
              process::exit(0); 
      }
} 

main.rs

mod my_mod.rs
fn main(){
  my_mod::my_mod::test();     
}

But it didn’t work, the compiler keeps saying that it doesn’t know “std::process”


#5

Hi there. Kindly use markdown while sharing code here.


#6

Read https://manishearth.github.io/blog/2017/05/14/mentally-modelling-modules/ - it’ll help you understand the scoping and the rules.