kyclark / command-line-rust

Code for Command-Line Rust (O'Reilly, 2024, ISBN 9781098109417)
https://learning.oreilly.com/library/view/command-line-rust/9781098109424/
MIT License
1.53k stars 251 forks source link

Chapter 8 "cutr": I'm confused why we're using `Option::map` and `Option::transpose` #23

Open atc0005 opened 3 months ago

atc0005 commented 3 months ago

@kyclark,

First, many thanks for writing this book and your ongoing support of it. I'm working through the 2024 edition and am learning a lot.

I'm in chapter 8 on page 182-183 and am reviewing how you incorporated the parse_pos function into the run function.

I understand what this code block is doing:

https://github.com/kyclark/command-line-rust/blob/10d983f68e84b9c94057da6ecf555bc419e11999/08_cutr/src/main.rs#L69-L84

but I don't understand why we wouldn't use an approach like this instead:

    let extract: Extract = if let Some(fields) = args.extract.fields {
        Extract::Bytes(parse_pos(fields)?)
    } else if let Some(bytes) = args.extract.bytes {
        Extract::Chars(parse_pos(bytes)?)
    } else if let Some(chars) = args.extract.chars {
        Extract::Fields(parse_pos(chars)?)
    } else {
        unreachable!("Must have --fields, --bytes, or --chars");
    };

I feel like I'm missing something. Does your implementation handle a scenario I'm missing, is it more idiomatic, are you just introducing your readers to additional corners of Rust that they might not encounter otherwise?

Again, many thanks for the book and thanks in advance for any insights you can share.

Makuo12 commented 1 week ago

Hey @atc0005 The call to parse_pos returns a type Option<Result<T, E>> transpose function converts it to a type Result<Option, E>. Converting it to a type Result<Option, E> is simply preferable for error handling because a ? is used if parse_pos returns an error, which means the error will propagate instantly without requiring additional error handling logic. Although the one in the book is cleaner, your version of the code still functions well.