Click a card to flip it · 10 terms
Functions are reusable blocks of code that perform a task. This deck covers how to define them with fn, pass values as parameters, and return results.
fn
The keyword that starts a function definition
Every function you write
fn greet() { println!("hi"); }fn add(a: i32) -> i32 { a + 1 }
A named block of code with typed inputs and optional output
Any time you want reusable logic
fn double(n: i32) -> i32 { n * 2 }let result = double(5);
A typed input slot in the function signature: name: &str
name: &str
What goes inside the () when defining a function
()
fn add(a: i32, b: i32) -> i32 { a + b }// a and b are parameters
The actual value passed when calling: "Shane"
"Shane"
When you call a function
greet("Shane", 30);// "Shane" and 30 are arguments
The type of value a function sends back
Declared after ->, if you declare it, you must return it
->
fn add(a: i32, b: i32) -> i32 {a + b } // -> i32 is the return type
Sends a value back to the caller and exits the function
At the end of a function that gives something back
fn double(n: i32) -> i32 { return n * 2; }// exits and sends n * 2 back
The last expression without a semicolon is returned automatically
Leave off the semicolon on the last expression; Rust returns it
fn double(n: i32) -> i32 {n * 2 // implicit return
The block of code where a variable is valid, from its declaration to the closing }
}
A variable declared inside { } cannot be used outside that block
{ }
{ let x = 5; }// x is gone outside the braces
A function that never returns to the caller, its return type is !
!
When a function always panics, loops forever, or exits the program
fn crash() -> ! { panic!("broken"); }fn run() -> ! { loop {} }
The return type of a function that never returns
fn never_return() -> ! { panic!() }
fn forever() -> ! { loop {} }fn crash() -> ! { panic!(); }