Skip to content

Latest commit

 

History

History
97 lines (68 loc) · 3.85 KB

06. functions_and_modules.md

File metadata and controls

97 lines (68 loc) · 3.85 KB

6. Functions and Modules: Building Modular and Reusable Code

Defining Functions in Rust

Functions in Rust are declared using the fn keyword followed by the function name, parameters, return type (optional), and function body. Here's a basic example:

fn greet(name: &str) {
    println!("Hello, {}!", name);
}
  • The fn keyword indicates the start of a function declaration.
  • Parameters are specified within parentheses after the function name.
  • The function body contains the code to be executed when the function is called.

Function Parameters and Return Values

Rust functions can have parameters and return values, allowing for flexible and reusable code. Parameters are passed by reference by default to prevent unnecessary copying of data. Here's an example:

fn add(x: i32, y: i32) -> i32 {
    x + y
}
  • Parameters are defined with their names and types within parentheses after the function name.
  • The -> arrow syntax is used to specify the return type of the function.

Function Overloading and Polymorphism

Rust does not support traditional function overloading like some other languages. Instead, Rust achieves polymorphism through generics and traits. This allows for flexible and generic functions that can operate on different types. Here's a simple example using generics:

fn print<T>(value: T) {
    println!("{}", value);
}
  • The <T> syntax declares a generic type parameter.
  • The function can then accept arguments of any type that implements the Display trait.

Modules and the mod Keyword

Modules in Rust allow you to organize code into separate namespaces, making it easier to manage larger projects. You can create modules using the mod keyword followed by the module name and its contents. Here's an example:

mod math {
    pub fn add(x: i32, y: i32) -> i32 {
        x + y
    }
}
  • Modules are declared using the mod keyword followed by the module name.
  • The pub keyword is used to specify that the function is accessible from outside the module.

Organizing Code into Modules and File System

Rust follows a convention-based approach for organizing code into modules and files. Each Rust file corresponds to a module, and the directory structure reflects the module hierarchy. This allows for clear and intuitive code organization. Here's an example directory structure:

src/
├── main.rs
└── math/
    ├── mod.rs
    └── operations.rs

Visibility and Access Control

Rust provides visibility modifiers (pub and priv) to control the visibility of functions, types, and modules. This ensures encapsulation and helps prevent unintended access to internal implementation details. Here's an example:

mod math {
    pub fn add(x: i32, y: i32) -> i32 {
        x + y
    }
}
  • The pub keyword makes the add function accessible from outside the module.

Best Practices

  • Keep functions small and focused on a single task for better readability and maintainability.
  • Use parameters and return values to make functions reusable across different parts of your codebase.
  • Organize code into modules and files based on functionality to improve code organization and maintainability.
  • Use visibility modifiers (pub and priv) judiciously to control access to your code's internals.

Real-World Example

Imagine you're developing a library for mathematical operations in Rust. You use modules to organize functions related to addition, subtraction, multiplication, etc., and provide clear visibility controls to ensure the library's users only access the intended functionality.

Conclusion

Functions and modules are essential building blocks of Rust programming, enabling code reuse, organization, and encapsulation. By mastering these concepts, you'll be able to write modular, maintainable, and scalable Rust code with confidence.