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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  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.

Ayush Mishra user avatar by
Ayush Mishra
·
May. 15, 19 · Tutorial
Like (1)
Save
Tweet
Share
11.93K 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.

Popular on DZone

  • Practical Example of Using CSS Layer
  • Fixing Bottlenecks in Your Microservices App Flows
  • Microservices 101: Transactional Outbox and Inbox
  • Low-Code Development: The Future of Software Development

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: