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