Sunday, January 26, 2020

Learning Rust - Day 8 - An I/O Project: Building a Command Line Program

This is the 8th journal entry of my learning Rust journey. It captures some of the learning points while going through chapter 12 of the Rust Book. You can read other posts in this series by following the label learning rust.

Not much new concepts was introduced in this chapter. The aim was to apply the material presented in the book up till that point in building a trivial command line tool.

While working through the chapter though, I observed a couple of different strategies for dealing with errors via the Result<T,E> type.

Turn error to boolean via is_err
This seems handy when you want to convert the result to boolean based on whether the result was a success of not:

let x: Result<i32, &str> = Ok(-3);
assert_eq!(x.is_err(), false);

let x: Result<i32, &str> = Err("Some error message");
assert_eq!(x.is_err(), true);

Get success or run some logic via unwrap_or_else
This allows getting the success value, and in case of error, allows passing a callback function to process the error.

fn count(x: &str) -> usize { x.len() }

assert_eq!(Ok(2).unwrap_or_else(count), 2);
assert_eq!(Err("foo").unwrap_or_else(count), 3);

Ignore success and only run some code on failure via if let syntax
This seems to be useful in cases where you only want to do something in case calling a function returns an error.

if let Err(e) = run(config) {
    eprintln!("Application error: {}", e);

These are by far not all the available error handling strategies when dealing with Result in Rust. These were only the ones that I picked on while reading through chapter 12.

Another thing worth nothing, which is more or less like a culture shock, is the practice of putting unit tests in the same file as the code being testes. All languages I have used before now had the practice of having the tests external to the code being tested; but it seems in idiomatic Rusts, the tests go together with the implementation. This would require some getting used to!

That was it for this chapter. I now look forward to exploring the Functional Language Features in Rust as I proceed to chapter 13..

1 comment:

Alice Wong said...

The caliber of information that you're offering is merely wonderful.