pub Keyword 🎯Welcome to our deep dive into the world of Rust! Today, we're focusing on the pub keyword, a crucial part of organizing your code in Rust. Let's get started!
pub Keyword? 📝In Rust, the pub keyword stands for "public". When you mark a variable, function, or module as pub, it can be accessed from other parts of your code.
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}In the above example, we have a public function greet(). Now, let's see how to call this function from another module.
Rust organizes your code into modules. A module can contain other modules, functions, and variables. You can think of a module as a container for your code.
// Defining a module called "my_lib"
pub mod my_lib {
// Defining a public function called "greet" inside the "my_lib" module
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
}Now, let's use the greet() function from the my_lib module in another file:
// Importing the "greet" function from "my_lib"
use my_lib::greet;
fn main() {
greet("Alice");
}priv) vs Public (pub) 💡If you don't use the pub keyword, by default, your items are private. Private items can only be accessed within their own module or if they are used as an item of a public item.
// Defining a module called "my_lib"
pub mod my_lib {
// Defining a private function called "private_greet"
fn private_greet(name: &str) {
println!("Hello, {}!", name);
}
// Making the "greet" function public
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
}Now, let's try to call the private_greet() function from the main() function. It won't work since private_greet() is private and can only be accessed within the my_lib module:
fn main() {
my_lib::private_greet("Alice"); // Error: the function is not public
}You can import a module and re-export it with a different name. This is useful when you want to use the same code structure in multiple projects.
// Defining a module called "my_lib"
pub mod my_lib {
pub mod greetings {
pub fn greet(name: &str) {
println!("Hello, {}!", name);
}
}
}
// In another file, importing the "greetings" module and renaming it to "greeting_module"
use my_lib::greetings as greeting_module;
fn main() {
greeting_module::greet("Alice"); // Accessing the "greet" function via the renamed "greeting_module"
}What does the `pub` keyword stand for in Rust?
What happens if you don't use the `pub` keyword in Rust?
By now, you should have a good understanding of the pub keyword in Rust and how it helps you organize your code. Remember to use it wisely and thoughtfully when working with modules and functions. Happy coding! 🎉