In this lesson, you’ll learn how to define functions in Rust, work with parameters, return values, and understand the differences between statements and expressions. Functions are essential building blocks that allow you to break your code into modular, reusable units, making your programs easier to manage and maintain. Think of functions as small machines: you provide inputs to the function, it processes the data, and then produces an output. For example, a coffee machine receives water and coffee beans (inputs), processes them, and then delivers a cup of coffee (output). This analogy perfectly encapsulates how functions operate in programming.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Defining Functions in Rust
In Rust, functions are defined using thefn keyword, followed by the function name, parameters (if any) enclosed in parentheses, and a body enclosed in curly braces. Below is a basic example of a function definition:
A Simple Function Example
Every Rust program starts with themain function, which serves as the entry point. In the example below, the main function calls another function named greet. This demonstrates how functions can be separated for clarity and reusability.
- The
mainfunction is the starting point for execution. - The
greetfunction is defined without parameters (as indicated by the empty parentheses) and contains a single instruction that prints “Hello, world!” to the console using theprintln!macro.
The simple
greet function illustrated above is an excellent starting point for understanding function definitions in Rust. In upcoming sections, we will expand on this foundation to include functions with parameters and detailed return values.