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"));
}
Comments
Post a Comment