FUNCTIONS

 FUNCTIONS


  • fn main() {
        println!("Hello, world!");
    
        another_function();
    }
    
    fn another_function() {
        println!("Another function.");
    }
    
  • The above code shows a basic function in rust which contains the keyword fn followed by function name and paranthesis for accepting parameters. The curly bracket which represents the scope of the function.
  • fn another_function() -> String{
         String::from("Grape")
    }
  • The above function doesn't have return keyword because, rust takes the last line with no semi-colon at the end as the return value.
  • You can call  the above function using below code:
  • fn main(){
    let fruit: String = another_function();
    }
  • In rust function with no return type is called unit type.
  • Arguments can be added to the function in the given below format.
  • fn another_function(fruit: String)->String{
        format!("Fruit {}", fruit)
    }
    
    fn main(){
        let fruit: String = another_function(fruit:String::from("Grape"));
    println!("Fruit{}", fruit);
    }
  • Rust supports inline functions (function inside function) too like given below.
  • fn main(){
       let fruit: |&str| -> String = |fruit: &str| format!("Fruit {}", fruit);
       println!("{}", fruit("Grapes"));
    }
  • Inline function can take more than one line like below:
  • fn main(){
       let fruit: |&str| -> String = |fruit: &str| {
    
    format!("Fruit {}", fruit);
    } }
  • Functions can be used as a parameter as given below
  • fn process_name(name: &str, callback: fn(&str)->()){
        callback(name);
    }
    fn main(){
    
    }
  • You can point to a function like you can would to a variable.
  • fn main(){
       let fruit: |&str| -> String = |fruit: &str| format!("Fruit {}", fruit);
       let fruit2: |&str| -> String = fruit;
       let result: &str = fruit2("grape");
    }

Comments