Functions Flashcards
How to define a function
fn function_name (param 1, param 2){
}
How to invoke a function
let x: u32= 10;
print_age(x);
fn print_age(age: u32){
println!(“Age: {}”, age)
}
How to return a value of a function
println!(“Pi value is: {}”, get_pi_value());
fn get_pi_value() -> f64{
22/7
}
Parameters can be passed to a function in how many techniques
Pass by value
Pass by reference
Example of pass by value
fn main(){
let no:i32 = 5;
mutate_no_to_zero(no);
println!(“The value of no is:{}”,no);
}
fn mutate_no_to_zero(mut param_no: i32) {
param_no = param_no*0;
println!(“param_no value is :{}”,param_no);
}
Example is pass by reference
let mut age: u32 = 19;
age_next_year(& mut age);
println!(“Age next year: {}” age)
fn age_next_year(age: &mut u32){
*age +=1;
}