A Beginner’s Guide to Rust: Functions and Modules

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.

💻 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 case f64 (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, and None, 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, and Err(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

Hello! I'm a gaming enthusiast, a history buff, a cinema lover, connected to the news, and I enjoy exploring different lifestyles. I'm Yaman Şener/trioner.com, a web content creator who brings all these interests together to offer readers in-depth analyses, informative content, and inspiring perspectives. I'm here to accompany you through the vast spectrum of the digital world.

Leave a Reply

Your email address will not be published. Required fields are marked *