Debug School

rakesh kumar
rakesh kumar

Posted on

Understanding Functions: Parameters, Return Values, and Scope in rust

What Is a Function in Rust?
Function Syntax
Functions with Parameters
Multiple Parameters
Returning Values
Functions That Don’t Return
Important Rules About Rust Functions
Full Example Program
Interview Questions & Answers on Rust Functions
MCQs – Basics and advanced

What Is a Function in Rust?

A function in Rust is a named block of code that performs a specific task. Functions help you:

Organize code into logical pieces

Reuse code

Improve readability and maintainability
Enter fullscreen mode Exit fullscreen mode

Every Rust program starts from the main function, which is the entry point.

Function Syntax

Rust functions are declared using the fn keyword:

fn function_name() {
    // body of the function
}

Enter fullscreen mode Exit fullscreen mode
fn — indicates a function definition

function_name — identifier (must use snake_case)

() — parameter list (can be empty)

{} — function body
Enter fullscreen mode Exit fullscreen mode

📌 Basic Example: Calling a Function

fn main() {
    say_hello();  // call the function
}

fn say_hello() {
    println!("Hello from a function!");
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

main calls say_hello

say_hello prints a message

💡

Functions with Parameters

Rust functions can accept parameters — they are like variables local to the function.

fn main() {
    greet("Ashwani");
}

fn greet(name: &str) {
    println!("Hello, {}!", name);
}
Enter fullscreen mode Exit fullscreen mode

name: &str — parameter with type annotation

Rust requires you to declare the type of each parameter

🔁

Multiple Parameters

fn main() {
    add(5, 7);
}

fn add(x: i32, y: i32) {
    println!("Sum is: {}", x + y);
}
Enter fullscreen mode Exit fullscreen mode

Parameters are separated by commas

Types must always be specified

🎯

Returning Values

Functions can return values by specifying a return type using ->.

fn main() {
    let result = multiply(4, 5);
    println!("Product is: {}", result);
}

fn multiply(a: i32, b: i32) -> i32 {
    a * b   // last expression is returned
}


-> i32 indicates return type
Enter fullscreen mode Exit fullscreen mode

The last expression (no semicolon) is returned

Note: You can also use return, but placing it at the end without a semicolon is idiomatic.

📌

Functions That Don’t Return

If a function doesn’t return a value, it implicitly returns the unit type ():

fn notify() {
    println!("This function returns nothing!");
}

Enter fullscreen mode Exit fullscreen mode

Functions with no return type automatically return ().

🔄 Example with Return and Control Flow

fn main() {
    let number = 5;
    let result = is_even(number);
    println!("Is {} even? {}", number, result);
}

fn is_even(n: i32) -> bool {
    n % 2 == 0  // returns true or false
}
Enter fullscreen mode Exit fullscreen mode

This example uses a function that returns a bool

The % operator checks even numbers

🧠

Important Rules About Rust Functions

✅ 1. Functions must declare parameter types

Rust requires explicit type annotations for all parameters so the compiler knows what types to expect.

✅ 2. Order of function definitions doesn’t matter

You can define a function before or after main. As long as it’s in scope, Rust will compile it.

✅ 3. Functions return the last expression

Rust treats the last expression as the return value if there’s no semicolon.

✅ 4. Functions improve modularity

Grouping related logic into functions makes programs easier to test, reuse, and maintain.

🧪

Full Example Program

fn main() {
    let a = 10;
    let b = 20;

    print_sum(a, b);

    let diff = subtract(a, b);
    println!("Difference is {}", diff);
}

fn print_sum(x: i32, y: i32) {
    println!("Sum is: {}", x + y);
}

fn subtract(x: i32, y: i32) -> i32 {
    y - x  // no semicolon: this gets returned
}
Enter fullscreen mode Exit fullscreen mode
✔ Runs without error
✔ Demonstrates functions with parameters and return values
Enter fullscreen mode Exit fullscreen mode

🧾

Key Takeaways

Functions in Rust start with fn.

You must specify types for parameters.

Functions can return values with ->.

Calling a function means writing its name + parentheses.

Interview Questions & Answers on Rust Functions

Basic Level

  1. What is a function in Rust?

Answer:
A function in Rust is a named block of code that performs a specific task. It helps organize code, avoid repetition, and improve readability.

  1. What is the entry point of a Rust program?

Answer:
The main function is the entry point of every Rust program.

fn main() {
    println!("Hello, Rust!");
}
Enter fullscreen mode Exit fullscreen mode

3.** How do you define a function in Rust?**

Answer:
Functions are defined using the fn keyword.

fn greet() {
    println!("Hello!");
}
Enter fullscreen mode Exit fullscreen mode
  1. Can a function be defined after it is called?

Answer:
Yes. Rust allows calling a function before or after its definition as long as it is in scope.

  1. Are parameter types mandatory in Rust functions?

Answer:
Yes. All function parameters must have explicit type annotations.

fn add(x: i32, y: i32) {
    println!("{}", x + y);
}
Enter fullscreen mode Exit fullscreen mode

Intermediate Level

  1. How do you pass arguments to a function?

Answer:
Arguments are passed inside parentheses when calling a function.

add(5, 10);
Enter fullscreen mode Exit fullscreen mode
  1. How does a function return a value in Rust?

Answer:
By specifying a return type using -> and returning the last expression without a semicolon.

fn square(n: i32) -> i32 {
    n * n
}

Enter fullscreen mode Exit fullscreen mode
  1. What is the unit type ()?

Answer:
The unit type () represents “no value.” Functions that do not return anything implicitly return ().

  1. What is the difference between statements and expressions in functions?

Answer:

Statements perform actions and do not return values.

Expressions evaluate to a value and can be returned.

let x = 5;   // statement
x + 1        // expression
Enter fullscreen mode Exit fullscreen mode
  1. Can a function return multiple values?

Answer:
Yes, by returning a tuple.

fn get_values() -> (i32, i32) {
    (10, 20)
}
Enter fullscreen mode Exit fullscreen mode

Advanced Level

  1. Why does Rust treat the last expression as a return value?

Answer:
It encourages a functional programming style, reduces boilerplate, and improves readability.

  1. Can functions have mutable parameters?

Answer:
Yes, but you must explicitly declare them as mutable.

fn increment(mut x: i32) -> i32 {
    x += 1;
    x
}
Enter fullscreen mode Exit fullscreen mode
  1. How does Rust ensure safety in function calls?

Answer:

By enforcing:

Strict type checking

Ownership and borrowing rules

Compile-time validation
Enter fullscreen mode Exit fullscreen mode
  1. What happens if a function declares a return type but doesn’t return a value?

Answer:
Compilation fails with a type mismatch error.

  1. How are control flow and functions related in Rust?

Answer:
Functions often use control flow (if, loop, while, for) to decide what value to return.

fn check_number(n: i32) -> &'static str {
    if n > 0 {
        "Positive"
    } else {
        "Non-positive"
    }
}
Enter fullscreen mode Exit fullscreen mode

Part 2: MCQs on Rust Functions (With Answers)

MCQs – Basics

  1. Which keyword is used to define a function in Rust?
A. function
B. def
C. fn
D. func
Enter fullscreen mode Exit fullscreen mode

✅ Answer: C

  1. What is the return type of a function that returns nothing?
A. void
B. null
C. ()
D. None

Enter fullscreen mode Exit fullscreen mode

✅ Answer: C

  1. Which function is the entry point of a Rust program?
A. start()
B. init()
C. main()
D. run()

Enter fullscreen mode Exit fullscreen mode

✅ Answer: C

  1. Are function parameter types optional in Rust?
A. Yes
B. No
C. Sometimes
D. Only for integers
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

MCQs – Return Values

  1. Which function correctly returns a value?

A.

fn add(x: i32, y: i32) {
    x + y
}


B.

fn add(x: i32, y: i32) -> i32 {
    x + y
}


C.

fn add(x: i32, y: i32) -> i32 {
    x + y;
}


D.

fn add(x, y) -> i32 {
    x + y
}
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

  1. What does the absence of a semicolon indicate in a function?
A. End of function
B. Return value
C. Error
D. Comment
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

  1. Which is a valid return type in Rust?
A. void
B. i32
C. null
D. undefined
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

MCQs – Advanced

  1. What happens if a function has a return type but no return value?
A. Program runs normally
B. Returns default value
C. Compile-time error
D. Runtime panic
Enter fullscreen mode Exit fullscreen mode

✅ Answer: C

  1. Which allows returning multiple values?
A. Array
B. Tuple
C. Struct
D. Enum
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

  1. Which statement is true about Rust functions?
A. Functions can omit parameter types
B. Functions must be defined before use
C. Last expression can be returned without return
D. Functions can change variable types
Enter fullscreen mode Exit fullscreen mode

✅ Answer: C

  1. What is returned by this function?
fn demo() {
    println!("Hello");
}
Enter fullscreen mode Exit fullscreen mode
A. i32
B. bool
C. String
D. ()
Enter fullscreen mode Exit fullscreen mode

✅ Answer: D

  1. Which of the following improves code reuse?
A. Loops
B. Functions
C. Variables
D. Constants
Enter fullscreen mode Exit fullscreen mode

✅ Answer: B

One-Line Interview Summary

Rust functions enforce type safety, use expressions for return values, and integrate seamlessly with control flow to produce clean, safe, and predictable code.

Top comments (0)