Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
atc0005 opened this issue Jul 2, 2024 · 1 comment

Comments

@atc0005
Copy link

atc0005 commented Jul 2, 2024

@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:

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

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
Copy link

Makuo12 commented Oct 7, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants