可见性
默认情况下,模块中的项拥有私有的可见性(private visibility),不过可以加上
pub 修饰语来重载这一行为。模块中只有公有的(public)项可以从模块外的作用域
访问。
``rust,editable
// 一个名为my_mod的模块
mod my_mod {
// 模块中的项默认具有私有的可见性
fn private_function() {
println!("calledmy_mod::private_function()`”);
}
1. // 使用 `pub` 修饰语来改变默认可见性。
2. pub fn function() {
3. println!("called `my_mod::function()`");
4. }
6. // 在同一模块中,项可以访问其它项,即使它是私有的。
7. pub fn indirect_access() {
8. print!("called `my_mod::indirect_access()`, that\n> ");
9. private_function();
10. }
12. // 模块也可以嵌套
13. pub mod nested {
14. pub fn function() {
15. println!("called `my_mod::nested::function()`");
16. }
18. #[allow(dead_code)]
19. fn private_function() {
20. println!("called `my_mod::nested::private_function()`");
21. }
23. // 使用 `pub(in path)` 语法定义的函数只在给定的路径中可见。
24. // `path` 必须是父模块(parent module)或祖先模块(ancestor module)
25. pub(in my_mod) fn public_function_in_my_mod() {
26. print!("called `my_mod::nested::public_function_in_my_mod()`, that\n > ");
27. public_function_in_nested()
28. }
30. // 使用 `pub(self)` 语法定义的函数则只在当前模块中可见。
31. pub(self) fn public_function_in_nested() {
32. println!("called `my_mod::nested::public_function_in_nested");
33. }
35. // 使用 `pub(super)` 语法定义的函数只在父模块中可见。
36. pub(super) fn public_function_in_super_mod() {
37. println!("called my_mod::nested::public_function_in_super_mod");
38. }
39. }
41. pub fn call_public_function_in_my_mod() {
42. print!("called `my_mod::call_public_funcion_in_my_mod()`, that\n> ");
43. nested::public_function_in_my_mod();
44. print!("> ");
45. nested::public_function_in_super_mod();
46. }
48. // `pub(crate)` 使得函数只在当前 crate 中可见
49. pub(crate) fn public_function_in_crate() {
50. println!("called `my_mod::public_function_in_crate()");
51. }
53. // 嵌套模块的可见性遵循相同的规则
54. mod private_nested {
55. #[allow(dead_code)]
56. pub fn function() {
57. println!("called `my_mod::private_nested::function()`");
58. }
59. }
}
fn function() {
println!(“called function()“);
}
fn main() { // 模块机制消除了相同名字的项之间的歧义。 function(); my_mod::function();
1. // 公有项,包括嵌套模块内的,都可以在父模块外部访问。
2. my_mod::indirect_access();
3. my_mod::nested::function();
4. my_mod::call_public_function_in_my_mod();
6. // pub(crate) 项可以在同一个 crate 中的任何地方访问
7. my_mod::public_function_in_crate();
9. // pub(in path) 项只能在指定的模块中访问
10. // 报错!函数 `public_function_in_my_mod` 是私有的
11. //my_mod::nested::public_function_in_my_mod();
12. // 试一试 ^ 取消该行的注释
14. // 模块的私有项不能直接访问,即便它是嵌套在公有模块内部的
16. // 报错!`private_function` 是私有的
17. //my_mod::private_function();
18. // 试一试 ^ 取消此行注释
20. // 报错!`private_function` 是私有的
21. //my_mod::nested::private_function();
22. // 试一试 ^ 取消此行的注释
24. // Error! `private_nested` is a private module
25. //my_mod::private_nested::function();
26. // 试一试 ^ 取消此行的注释
}
