DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Rust-Native Alternatives to Spark SQL and DataFrame Workloads
  • Imprisoning the Panic
  • Concurrency in Rust: Writing Safe and Efficient Code
  • Rust, WASM, and Edge: Next-Level Performance

Trending

  • How to Interpret the Number of Spring ApplicationContexts in Integration Tests
  • Prompt Injection Is Real, So I Built a Python Firewall for LLM Pipelines
  • Persistent Memory for AI Agents Using LangChain's Deep Agents
  • Architecting Proactive IT: NinjaOne Remote Monitoring and Management
  1. DZone
  2. Coding
  3. Languages
  4. Different Ways for 'Error Propagation' in Rust

Different Ways for 'Error Propagation' in Rust

See three different ways for error propagation in Rust.

By 
Ayush Mishra user avatar
Ayush Mishra
·
May. 15, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
13.1K Views

Join the DZone community and get the full member experience.

Join For Free

Error Propagation means the code that detects the problem must propagate error information back to the caller function so that it can handle the problem. In the real world, the practice of Error Propagation is necessary. One of the benefits is that your code will look cleaner by simply propagating error information back to the caller that can handle the error. Another benefit is that your function doesn't need extra code to propagate both the successful and unsuccessful cases back to the caller. I won't go into details of this concept.

In this article, I will explain how you can do this in Rust in different ways.

  1. Using match 
use std::fs::File;
use std::io::Error;

fn open_file() -> Result<(), Error> {
    let file: Result<File, Error> = File::open("hello.txt");
    match file {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

fn main() {
    match open_file() {
        Ok(_) => println!("File is opened successfully!"),
        Err(e) => panic!(
            "Not able to open file. Here is the reason {:?}",
            e.to_string()
        ),
    }
}

If you are Rust developer, you would have known Result type, which is used to handle recoverable errors. In the above example, we are trying to open the file. File::open returns Result<File, Error>. We handle this value using match. If the file opened successfully, open_file will return Ok otherwise, pass the error value back to the caller function. Now caller function has to decide what to do with this error value. It can either create a new file hello.txt or show an error message.

2) Using try! 

The above example can be written in a much shorter way. Let's try with try. try! is a macro that returns Errs automatically in case of error otherwise it returns Ok variant. To use this macro, you have to use the raw-identifier syntax: r#try.

fn open_file() -> Result<(), Error> {
    let file = r#try!(File::open("hello.txt"));
    Ok(())
}

try! unwraps a result and early returns the function, if an error occurred.

3) Using ?operator 

We can even shorten above code using ? operator. This operator was added to replace try! and it's more idiomatic to use ? instead of try!.

fn open_file() -> Result<(), Error> {
    let file = File::open("hello.txt")?;
    Ok(())
}

As you can see this eliminates a lot of boilerplate and makes implementation simpler. I hope you enjoy reading this article. Let me know your thoughts in the comments!

Rust (programming language)

Published at DZone with permission of Ayush Mishra. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Rust-Native Alternatives to Spark SQL and DataFrame Workloads
  • Imprisoning the Panic
  • Concurrency in Rust: Writing Safe and Efficient Code
  • Rust, WASM, and Edge: Next-Level Performance

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook