Super and Self Keywords in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Whenever we want to remove the tedious long importing paths of functions that we want to invoke, either from the same function or from a different module, we can make use of the super and self keywords provided in Rust.

These keywords help in removing the ambiguity when we want to access the items and also prevent unnecessary hardcoding of paths.

Example

Consider a simple example shown below:

fn function() {
   println!("called `function()`");
}
mod cool {
   pub fn function() {
      println!("called `cool::function()`");
   }
}
mod my {
   fn function() {
      println!("called `my::function()`");
   }
   mod cool {
      ub fn function() {
         println!("called `my::cool::function()`");
      }
   }

   pub fn my_call() {
      // Let's access all the functions named `function` from this scope!
      print!("called `my::my_call()`, that\n> ");
      self::function();
      function();
      // We can also use `self` to access another module inside `my`:
      self::cool::function();
      super::function();
      // This will bind to the `cool::function` in the *crate* scope.
      // In this case the crate scope is the outermost scope.
      {
         use crate::cool::function as root_function;
         root_function();
      }
   }
}
fn main() {
   my::my_call();
}

When we are making use of the self keyword, it is referring to the current module scope and hence, there isn’t any difference in calling self::function() and function().

When we append the super keyword in front of invoking the function, we are trying to refer to the parent scope (or another module).

Output

called `my::my_call()`, that
> called `my::function()`
called `my::function()`
called `my::cool::function()`
called `function()`
called `cool::function()`
raja
Published on 05-Apr-2021 07:40:12
Advertisements