Reading The Rust Book from cover to cover — Day 5 — Functions
2 min readApr 10, 2024
Functions
Functions in Rust are defined with the keyword fn
. The structure and syntax are the same as most of the other languages. Rust uses asnake_case
convention for multi-word function names.
Function examples:
fn main() {
println!("Hello, world!");
another_function();
another_function_1(12);
}
//function without paramaters
fn another_function() {
println!("Another function.");
}
//function with one parameter
fn another_function_1(x: i32) {
println!("The value of x is: {x}"); //output: The value of x is: 12
}
//function with multiple parameters
fn print_labeled_measurement(value: i32, unit_label: char) {
println!("The measurement is: {value}{unit_label}");
}
Statements and Expressions in Rust
- Statements are instructions that perform some action and do not return a value.
- Expressions evaluate to a resultant value.
Examples of statements: creating a variable, assigning a value to it with a let
keyword as they do not return a value.
Examples of expressions: 5 + 6, calling a function, calling a macro, a new scope block created with {}. Expressions do not contain an ending semicolon, adding a semicolon turns an expression to a…