Greetings, code enthusiasts! On Day 7 of my #100DaysOfCode journey with Rust, let's dive into the world of functions - the building blocks of any great code composition.
Declaring Functions: The Rustic Way π οΈ
In Rust, functions start with the fn
keyword, followed by a name, parentheses, and curly braces. You've already met the star of the show, the main function - the entry point of every Rust program:
fn main() {
greet();
}
fn greet() {
println!("Greetings, Rustacean!");
}
Quick Notes on Rustic Etiquette π
Function names in Rust embrace
snake_case
: all lowercase with underscores between words.Choose names that are both descriptive and expressive to convey the function's purpose clearly.
Avoid starting function names with numbers for the sake of readability.
Adding Flavor: Functions with Parameters πΆοΈ
Let's spice things up with functions that take parameters:
fn main() {
greet("John Doe");
}
fn greet(name: &str) {
println!("Greetings, {name}!!");
}
Note: Explicitly mention the parameter type for a dash of clarity.
Return of the Function: Functions with Return Values π
Witness the grand return of functions with values:
fn main() {
let result = add(10, 20);
println!("The sum is {}", result);
}
fn add(a: i32, b: i32) -> i32 {
a + b
}
Note: Indicate the return type after an arrow
->
for a spectacular finale.
As the symphony of functions continues to play in Rust, I find joy in crafting code with clarity and purpose. Join me on Github for more updates! π»πβ¨
Top comments (0)