Best way to handle error in this specific case

I'm still a very new Rustacean but I've built a few projects now and for my current project I'd like to do some proper error handling. I haven't decided yet if I'm going to make use of thiserror or snafu or just roll my own this time (error-chain looks too scary for now) but I have a particular case where I'm not really sure what to do. The code looks like this:

const COLUMN_LETTERS: [char; 26] = [
    'A', 'B', 'C', 'D', 'E', 
    'F', 'F', 'H', 'I', 'J', 
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T', 
    'U', 'V', 'W', 'X', 'Y', 
    'Z',
];

pub fn cols(cols: &Vec<char>) -> Vec<usize> {
    let indices: Vec<usize> = cols.iter().map(|&c| {
        COLUMN_LETTERS.iter()
            .position(|&l| l == c)
            .expect("unable to get column index")
    }).collect();
    indices
}

Calling position returns an Option<usize> and what I need is that if this position call returns None, the cols function should return an error and the program should fail. I would like this function to return an error from within the closure if position results in None but I'm wondering what the best way to do that is. Is it better/easier to do this from within a for loop instead of using map here? Also, I'd be interested to know if thiserror or snafu are easier to implement in this kind of situation.

Thanks!

You can easily transform this to return an Option

const COLUMN_LETTERS: [char; 26] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'F', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];

pub fn cols(cols: &[char]) -> Option<Vec<usize>> {
    cols.iter()
        .map(|&c| COLUMN_LETTERS.iter().position(|&l| l == c))
        .collect()
}

To return a Result you can then use ok_or.

You can transform the inner Option to a Result and return Result<Vec<usize>>. playground

1 Like
pub fn cols(cols: &[char]) -> Option<Vec<usize>> {
    cols.iter()
        .map(|&c| COLUMN_LETTERS.iter().position(|&l| l == c))
        .collect()
}

What's happening in this case? If any of the position calls return None then the whole thing is None?

This is short circuiting (both for collecting to Option or Result), at the first None or Err, the iteration will stop and return None or the Err.

1 Like

Got it, that makes sense. Thank you! :slightly_smiling_face:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.