keyword

Rust fn: declare a function

A function is a named piece of code that can be called repeatedly. Define one with `fn`; parameters supply input and the return type describes its result. Expected output: 14 Why: The call supplies 7 to n; the final expression returns twice that value. Common mistake: Adding a semicolon to this final expression would produce unit instead of i32.

Formal Syntax & Structure

rust syntaxrust
fn name(parameter: Type) -> Type { expression }

Working Example

Example Snippetrust
fn double(n: i32) -> i32 {    n * 2}
fn main() {    println!("{}", double(7));}
Rust Reference