Functions Exercises

Overview

These exercises cover function declaration, parameters, return types, and Rust’s expression-based returns.


functions1 - Basic Function Declaration

Concept: Defining a simple function

fn call_me() {
    println!("Hello world!");
}
 
fn main() {
    call_me();
}

Key Takeaway: Functions are defined with fn followed by the name and parentheses.


functions2 - Function Parameters

Concept: Type annotations for parameters

fn call_me(num: u64) {  // Type annotation is required!
    for i in 0..num {
        println!("Ring! Call number {}", i + 1);
    }
}
 
fn main() {
    call_me(3);
}

Key Takeaway: Function parameters must have explicit type annotations — Rust doesn’t infer them.


functions3 - Calling with Arguments

Concept: Matching arguments to parameters

fn call_me(num: u8) {
    for i in 0..num {
        println!("Ring! Call number {}", i + 1);
    }
}
 
fn main() {
    call_me(5);  // Must provide the argument!
}

Key Takeaway: If a function expects an argument, you must pass one.


functions4 - Return Types

Concept: Annotating return types with ->

fn is_even(num: i64) -> bool {
    num % 2 == 0
}
 
fn sale_price(price: i64) -> i64 {  // Return type annotation
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}
 
fn main() {
    let original_price = 51;
    println!("Your sale price is {}", sale_price(original_price));
}

Key Takeaway: Return types must be annotated with -> Type in the function signature.


functions5 - Implicit Returns (Expressions)

Concept: Returning without return keyword

fn square(num: i32) -> i32 {
    num * num  // No semicolon = this is the return value
}
 
fn main() {
    let answer = square(3);
    println!("The square of 3 is {answer}");
}

Key Takeaways:

  • Rust is expression-based — the last expression without a semicolon is the return value
  • Adding a semicolon turns an expression into a statement (returns ())
  • You can use return explicitly, but idiomatic Rust prefers the implicit form
With ;Without ;
Statement, returns ()Expression, returns value

Rust Book Reference