Home » Rust Making a Function Public

Rust Making a Function Public

by Online Tutorials Library

Making a functioning public

The “pub” keyword is used at the starting of the declaration so that the function becomes accessible to the outside functions.

Following are the privacy rules:

  • If any function or module is public, then it can be accessed by any of the parent modules.
  • If any function or module is private, then it can be accessed either by its immediate parent module or by the parent’s child module.

Let’s understand this through a simple example:


Rust Making a functioning public

In the above example, the main() function is the root module while an outer module is the current root module of our project. Therefore, the main() function can access the outer module.

The call to outer::a() will not cause any error as the function a() is public, but when the main() function tries to access the outer::b() function, then it causes the compilation error because it is a private function.

The main() function cannot access the inner module as it is private. An inner module has no child module, so it can be accessed only by its parent module, i.e., outer module.

Next TopicRust use Keyword

You may also like