[Rust] Function
Rust's function is the same as other languages.
The main() function is the most important function and it is the entry point of programs.
Define Function
fn keyword allows us to declare new functions.
The naming convention of the function is snake case.
fn main() {
println!("main() function");
test();
}
fn test() {
println!("test() function");
}
Parameters and Return Values
We can define functions to have parameters and return values.
Specifying parameters is the same as specifying variables.
Specifying return value is more simple.
We don't name return values, but we must declare their type after an arrow.
Function bodies are made up of a series of statements optionally ending in an expression when there is a specified return value.
fn main() {
let y = test(5);
println!("main(): {y}"); // 6
}
fn test(x: i32) -> i32 {
println!("test(): {x}"); // 5
x + 1
}
Lifetime Annotations in Function
Every reference in Rust has a lifetime, which is the scope for which that reference is valid.
Rather than ensuring that a type has the behavior we want, lifetimes ensure that references are valid as long as we need them to be.
The names of lifetime parameters must start with an apostrophe and are usually all lowercase and very short, like generic types.
We place lifetime parameter annotations after the ampersand of a reference, using a space to separate the annotation from the reference's type.
fn adder<'a, 'b>(x: &'a u32, y: &'b u32) -> u32 {
x + y
}
fn main() {
let x: u32 = 3;
let y: u32 = 4;
let z = adder(&x, &y);
println!("{z}");
}
Generic Data Types in Function
The generics can be placed in the signature of the function where we would usually specify the data types of the parameters and return value.
To define the generic function, we should place type name declarations inside angle brackets between the function's name and the parameter list.
We use the letter T conventionally.
use std::ops::Add;
use std::time::Duration;
fn add<T: Add<Output = T>>(i: T, j: T) -> T {
i + j
}
fn main() {
let ints = add(1, 2);
println!("{ints}");
let floats = add(1.2, 3.4);
println!("{floats}");
let durations = add(Duration::new(3, 0), Duration::new(7, 0));
println!("{durations:?}");
}