Rust Functions
🦀 Rust Functions
They help make programs clean, modular, and readable.
1. Defining a Function
Syntax
-
fn→ function keyword -
Function names use snake_case
-
Code block inside
{}
2. Function with Parameters
✔ Parameter types are mandatory
3. Function with Return Value
Important
-
-> i32defines return type -
Last expression (without
;) is returned -
returnkeyword is optional
4. Using return Keyword
✔ Useful for early returns
5. Multiple Parameters
6. Function as Expression
Functions can be used inside expressions.
7. Function Scope
Functions can be defined outside main().
✔ Rust does not allow nested named functions
8. Returning Multiple Values (Tuple)
9. Function with Option
10. Best Practices
✔ Use meaningful function names
✔ Keep functions small
✔ One function → one responsibility
✔ Use Option / Result for safety
🧠 Summary
-
fnkeyword defines function -
Types are mandatory for parameters
-
Functions return values via expressions
-
Encourages safe & clean code
