Lesson 8 of 50 · rust
Functions
Duration: 12 minutes
Lesson 8 of 50 · rust
Duration: 12 minutes
rust\nfn add(a: i32, b: i32) -> i32 {\n a + b\n}\n\n\nBreakdown:\n- fn keyword declares a function\n- Name: add\n- Parameters: (a: i32, b: i32) with types\n- Return type: -> i32\n- Last expression without semicolon is the return value\n\n## Parameters and Return Types\n\nAll parameters require type annotations. Return types aren't inferred:\n\nrust\nfn multiply(x: f64, y: f64) -> f64 {\n x * y // No semicolon—this is the return value\n}\n\nfn print_number(n: i32) {\n // No return type means returns unit ()\n println!(\"Number: {}\", n);\n} // Implicitly returns ()\n\n\n## Statements vs Expressions\n\nStatements end with semicolons and don't return values:\n\nrust\nlet x = 5; // Statement\nlet y = x + 1; // Expression (+ returns value)\n\n\nExpressions don't end with semicolons and return values:\n\nrust\n5 + 6 // Expression returning 11\n{\n let x = 3;\n x + 1 // Expression returning 4\n}\n\n\nAdding a semicolon turns an expression into a statement, changing the semantics.\n\n## Early Returns\n\nUse return keyword to exit early:\n\nrust\nfn check_number(n: i32) -> String {\n if n < 0 {\n return String::from(\"Negative\");\n }\n String::from(\"Positive\")\n}\n\n\n## Function Calls\n\nrust\nfn main() {\n let result = add(5, 7);\n println!(\"Sum: {}\", result); // Sum: 12\n}\n\nfn add(a: i32, b: i32) -> i32 {\n a + b\n}\n