As you become more comfortable with Rust, it’s time to explore its core building blocks: functions and modules. This guide will also uncover how Rust handles errors, a key feature that contributes to its reputation for reliability. Properly structuring your code with functions and modules is essential for writing clean, maintainable, and scalable applications.
Table of Contents
💻 Defining and Using Functions
A function declaration in Rust always begins with the fn
keyword. Every autonomous Rust program must have a main()
function, which is the entry point of execution. Functions can take arguments and return values, with strict type checking enforced by the compiler.
fn distance_2d(x1: i32, y1: i32, x2: i32, y2: i32) -> f64 {
let distance: f64 = (((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) as f64).sqrt();
return distance;
}
This example shows:
- Type annotations are required for all arguments, like
x1: i32
. - The return type is specified after an arrow
->
, in this casef64
(a 64-bit float). - Type casting is explicit, using the
as
keyword (as f64
).
💻 Handling Errors with `Option` and `Result`
Rust handles errors in a very explicit and robust way, without using exceptions. It primarily uses two special enum types provided by the standard library:
Option
: This is used when a value could be something or nothing. It has two variants:Some(T)
, which contains a value, andNone
, to indicate the absence of a value. This prevents null pointer errors common in other languages.Result
: This is used for operations that can fail. It has two variants:Ok(T)
, containing a success value, andErr(E)
, containing an error value.
To get the value out of these types, you use pattern matching with the match
keyword. This forces you to handle both the success and failure cases, leading to more reliable code.
let mut file = match File::open(&filename) {
Err(why) => panic!("couldn't open: {}", why.description()),
Ok(file) => file,
};
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes