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
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
}
fn — indicates a function definition
function_name — identifier (must use snake_case)
() — parameter list (can be empty)
{} — function body
📌 Basic Example: Calling a Function
fn main() {
say_hello(); // call the function
}
fn say_hello() {
println!("Hello from a function!");
}
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);
}
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);
}
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
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!");
}
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
}
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
}
✔ Runs without error
✔ Demonstrates functions with parameters and return values
🧾
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
- 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.
- 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!");
}
3.** How do you define a function in Rust?**
Answer:
Functions are defined using the fn keyword.
fn greet() {
println!("Hello!");
}
- 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.
- 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);
}
Intermediate Level
- How do you pass arguments to a function?
Answer:
Arguments are passed inside parentheses when calling a function.
add(5, 10);
- 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
}
- What is the unit type ()?
Answer:
The unit type () represents “no value.” Functions that do not return anything implicitly return ().
- 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
- Can a function return multiple values?
Answer:
Yes, by returning a tuple.
fn get_values() -> (i32, i32) {
(10, 20)
}
Advanced Level
- Why does Rust treat the last expression as a return value?
Answer:
It encourages a functional programming style, reduces boilerplate, and improves readability.
- Can functions have mutable parameters?
Answer:
Yes, but you must explicitly declare them as mutable.
fn increment(mut x: i32) -> i32 {
x += 1;
x
}
- How does Rust ensure safety in function calls?
Answer:
By enforcing:
Strict type checking
Ownership and borrowing rules
Compile-time validation
- What happens if a function declares a return type but doesn’t return a value?
Answer:
Compilation fails with a type mismatch error.
- 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"
}
}
Part 2: MCQs on Rust Functions (With Answers)
MCQs – Basics
- Which keyword is used to define a function in Rust?
A. function
B. def
C. fn
D. func
✅ Answer: C
- What is the return type of a function that returns nothing?
A. void
B. null
C. ()
D. None
✅ Answer: C
- Which function is the entry point of a Rust program?
A. start()
B. init()
C. main()
D. run()
✅ Answer: C
- Are function parameter types optional in Rust?
A. Yes
B. No
C. Sometimes
D. Only for integers
✅ Answer: B
MCQs – Return Values
- 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
}
✅ Answer: B
- What does the absence of a semicolon indicate in a function?
A. End of function
B. Return value
C. Error
D. Comment
✅ Answer: B
- Which is a valid return type in Rust?
A. void
B. i32
C. null
D. undefined
✅ Answer: B
MCQs – Advanced
- 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
✅ Answer: C
- Which allows returning multiple values?
A. Array
B. Tuple
C. Struct
D. Enum
✅ Answer: B
- 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
✅ Answer: C
- What is returned by this function?
fn demo() {
println!("Hello");
}
A. i32
B. bool
C. String
D. ()
✅ Answer: D
- Which of the following improves code reuse?
A. Loops
B. Functions
C. Variables
D. Constants
✅ 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)