The 'use' Keyword

The ‘use’ Keyword

Why Use the use Keyword?

The benefit is greatest when items in the same module need to be referred to in the code again and again. Now, we don’t have to type the entire path over and over.

The following example shows how we can write a precise code using a use keyword:

pub mod chapter {
    pub mod lesson { // mod level 1
        pub mod heading { // mod level 2
            pub fn illustration() {  // mod level 3
              println!("Hi, I'm a 3rd level nested function");
use chapter::lesson::heading; // make use of `use` keyword
fn main() {
    heading::illustration(); // call the function


Hi, I'm a 3rd level nested function

Glob Operator ( * )

The glob operator helps you to prevent writing EnumName::variant when assigning enum value to a variable.

the following example shows how we can avoid writing a lengthy code using the glob operator *.

// make this `enum` printable with `fmt::Debug`.


enum KnightMove{



use KnightMove::*; // use of globe operator

fn main() {

   // use enum

   let horizontal_move = Horizontal; // Horizontal is shortcut for KnightMove::Horizontal

   let vertical_move = Vertical; // Vertical is shortcut for KnightMove::Vertical

   // print the enum values

   println!("{:?}", horizontal_move);

   println!("{:?}", vertical_move);





Test your understanding of nested modules, the use keyword and the globe operator *!

  1. You can only nest the modules upto three levels.
    A) True
    B) False

  2. The followinng enum is declared ``` enum Gender { Male, Female }

How would you use the glob operator ?

use Gender :: *


Gender :: *

3. What is the output of the following code? <br>

pub mod chapter { pub mod lesson { pub fn summary(){ println!(“This is the summary”); } pub mod heading { pub fn illustration() {
println!(“Hi, I’m a 3rd level nested function”); } } } } use chapter::lesson::heading; use chapter::lesson;

fn main() { lesson::summary(); heading::illustration(); }


This is the summary Hi, I’m a 3rd level nested function


Hi, I’m a 3rd level nested function ```