🛠️ Functions in Rust


📌 Defining a Function

rust
Loading…
  • Function names use snake_case by convention
  • Call a function with its name and parentheses

📥 Parameters

rust
Loading…

🎁 Return Values

rust
Loading…

✅ The last expression in a function is the return value—no return needed unless you want to return early.

If you do use return, add a semicolon:

rust
Loading…

❌ But if you end with an expression, do not use a semicolon:

rust
Loading…

⚙️ Statements vs Expressions

  • Statements do something but return nothing (e.g., let x = 5;).
  • Expressions evaluate to a value (e.g., 5 + 2, x * y, blocks like ).

Since Rust is expression-oriented, you can use blocks to return values:

rust
Loading…

💡 Why Functions Matter

  • Make your code easier to read and maintain
  • Help you organize logic into small, testable chunks
  • Allow you to reuse behavior across your app

Rust also supports advanced patterns like:

  • Function pointers
  • Closures (anonymous functions)
  • Higher-order functions

…but we’ll get there later 😎


🧠 Summary

  • Define functions with fn
  • Use parentheses () for parameters
  • Return values with -> and no semicolon on the last line
  • Embrace expressions—Rust loves them!

Mastering functions early will unlock a lot of power in your Rust journey 🦀