DEV Community

Cover image for Day 7: Unleashing Functions in Rust πŸš€
Aniket Botre
Aniket Botre

Posted on

Day 7: Unleashing Functions in Rust πŸš€

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!");
}
Enter fullscreen mode Exit fullscreen mode

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}!!");
}

Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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! πŸ’»πŸŒβœ¨

RustLang #Programming #LearningToCode #CodeNewbie #TechJourney #Day7

Top comments (0)