Rust Functions

Rust Tutorial

🦀 Rust Functions

Functions in Rust are reusable blocks of code that perform a specific task.

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

  • -> i32 defines return type

  • Last expression (without ;) is returned

  • return keyword 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

  • fn keyword defines function

  • Types are mandatory for parameters

  • Functions return values via expressions

  • Encourages safe & clean code

You may also like...