[Avg. reading time: 6 minutes]
Functions
Functions are the primary building blocks for readable, reusable, and maintainable code.
Rust functions are flexible in placement:
-
They can be defined before or after
main -
Order does not matter as long as they are in scope
-
Function names use snake_case
-
Parameters and return types are explicit
Simple Function
// Simple Function fn main(){ //calling a function hello(); } fn hello(){ println!("Hi"); }
Return a Value
// Return Value // Demonstrate the same with the return value (35000.00*5.0*6.4/100.00) fn main(){ println!("Hi {}",calc_si()); } fn calc_si()->f32 { 35000.00*5.0*6.4/100.00 }
- Return type is specified using ->
- No semicolon on the return expression
- All return paths must match the declared type
Call By Value
// Call by Value fn main(){ let no:i32 = 5; changeme(no); println!("Main Function:{}",no); } fn changeme(mut param_no: i32) { param_no = param_no * 0; println!("Inside the Function :{}",param_no); }
- i32 is copied into the function
- Changes inside the function do not affect the caller
- This is safe and predictable
Call By Reference
// Call by Reference fn main() { let mut no: i32 = 5; println!("Main fucntion initial value :{} -> {:p}", no,&no); changeme(&mut no); println!("Main function final value is:{} -> {:p}", no,&no); } fn changeme(param_no: &mut i32) { println!("Changeme function initial value :{} -> {:p}", *param_no,&(*param_no)); *param_no = 0; //de reference println!("Changeme function final value :{} -> {:p}", *param_no,&(*param_no)); }
- &mut creates a mutable reference
- * dereferences the reference
- Only one mutable reference is allowed at a time
Summary
- Functions are defined using fn
- Rust returns the last expression implicitly
- Values are passed by copy by default
- Use references to allow mutation without copying
- Borrowing rules are enforced at compile time