super and self

The super and self keywords can be used in the path to remove ambiguity
when accessing items and to prevent unnecessary hardcoding of paths.

  1. fn function() {
  2. println!("called `function()`");
  3. }
  4. mod cool {
  5. pub fn function() {
  6. println!("called `cool::function()`");
  7. }
  8. }
  9. mod my {
  10. fn function() {
  11. println!("called `my::function()`");
  12. }
  13. mod cool {
  14. pub fn function() {
  15. println!("called `my::cool::function()`");
  16. }
  17. }
  18. pub fn indirect_call() {
  19. // Let's access all the functions named `function` from this scope!
  20. print!("called `my::indirect_call()`, that\n> ");
  21. // The `self` keyword refers to the current module scope - in this case `my`.
  22. // Calling `self::function()` and calling `function()` directly both give
  23. // the same result, because they refer to the same function.
  24. self::function();
  25. function();
  26. // We can also use `self` to access another module inside `my`:
  27. self::cool::function();
  28. // The `super` keyword refers to the parent scope (outside the `my` module).
  29. super::function();
  30. // This will bind to the `cool::function` in the *crate* scope.
  31. // In this case the crate scope is the outermost scope.
  32. {
  33. use cool::function as root_function;
  34. root_function();
  35. }
  36. }
  37. }
  38. fn main() {
  39. my::indirect_call();
  40. }