Open In App

Rust – Super and Self Keywords

Rust is a multi-paradigm programming language like C++ syntax that was designed for performance and safety, especially safe concurrency by using a borrow checker and ownership to validate references. The self and super keywords provided by Rust can be used in the path to remove ambiguity when accessing items like functions.

Example:






// Rust program for Super & Self Keywords
fn function_with_same_name() {
    println!("called `function_with_same_name()`
      which is in the outermost scope");
}
 
mod cool_mod {
    pub fn function_with_same_name() {
        println!("called `cool_mod::function_with_same_name()`
          which is inside the `cool_mod` module in the outermost scope");
    }
}
 
mod my_mod {
    fn function_with_same_name() {
        println!("called `my_mod::function_with_same_name()`
          which is inside the `my_mod` module");
    }
     
    mod cool_mod {
        pub fn function_with_same_name() {
            println!("called `my_mod::cool_mod::
              function_with_same_name()` which is inside the
              `cool_mod` module which is in turn inside `my_mod` module");
        }
    }
     
    pub fn indirect_call() {
        // Let's access all the functions named
        //`function_with_same_name` from this scope!
        print!("called `my_mod::indirect_call()`, that\n> ");
         
        // The `self` keyword refers to the current module
        // scope - in this case `my_mod`.
        // Calling `self::function_with_same_name()` and
        // calling `function_with_same_name()` directly both give
        // the same result, because they refer to the same function.
        self::function_with_same_name();
        function_with_same_name();
         
        // We can also use `self` to access
        // another module inside `my_mod`:
        // We have `cool_mod` module inside `my_mod`
        // module which contains `function_with_same_name`
        self::cool_mod::function_with_same_name();
         
        // The `super` keyword refers to the parent scope
        // (outside the `my_mod` module).
        super::function_with_same_name();
         
    }
}
 
fn main() {
    my_mod::indirect_call();
}

Output:

 

Explanation:




Article Tags :