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.