4

I tried to run the following code snippet:

let a = &[Some(1), Some(2), Some(3), None, Some(4)];

let mut sum = 0;
for &Some(x) in a.iter() {
    sum += x;
}

assert_eq!(sum, 1+2+3+4);

The compiler replied with:

about_loops.rs:39:9: 43:18 error: non-exhaustive patterns: None not covered
about_loops.rs:39         for &Some(x) in a.iter() {
about_loops.rs:40             sum += x;
about_loops.rs:41         } 
about_loops.rs:42 
about_loops.rs:43         assert_eq!(sum, 1+2+3+4);
error: aborting due to previous error
make: *** [all] Error 101

Can I make such a construct compile for a for loop without using a match expression as suggested by luke and hobbs? Or is this error message misleading? It does not seem so given the grammar definition of for.

for_expr : "for" pat "in" expr '{' block '}' ;

I'm on:

rustc 0.11.0-pre-nightly (6291955 2014-05-19 23:41:20 -0700)
host: x86_64-apple-darwin

To clarify: How expressive is the 'pat' portion of for_expr? This is not specified under http://doc.rust-lang.org/rust.html#for-expressions in contrast to the definition under http://doc.rust-lang.org/rust.html#match-expressions.

5 Answers 5

3

The pattern of a for loop essentially has the same restrictions as a let: it has to be irrefutable, that is, it can't ever fail to match.

Examples of irrefutable patterns are &, tuples, structs and single-variant enums. Other patterns (like multivariant enums or literals) aren't guaranteed to always match, since the type allows for values that aren't covered by the pattern.

The for construct is essentially a macro that desugars as follows (it desugars in the same pass as macros are expanded, you can see it manually running rustc with --pretty expanded):

for <pattern> in <iter_expression> {
    <code>
}

// becomes

match &mut <iter_expression> { // match to guarantee data lives long enough
    it => {
        loop {
            match it.next() {
                None => break,
                Some(<pattern>) => { <code> }
            }
        }
    }
}

That is a normal match, i.e. the arms have to be exhaustive (cover every possibility), and so if <pattern> is just &Some(_), then the Some(&None) possibility isn't covered.

(The Some arm is essentially equivalent to Some(value) => { let <pattern> = value; .... Thinking about it now, this might actually be a desugaring that gives better error messages: I filed #14390.)

1

The Some is a type in an enum. The Option enum has two types, Some(T) and None. Your code assumes that a.iter() always is Some(T), and never checks for None. To add in the check, you can use an match. Something like this:

let a = &[Some(1), Some(2), Some(3), None, Some(4)];

let mut sum = 0;
for &j in a.iter() {
  match j {
    Some(x) => sum += x,
    None => ()
  }
}

assert_eq!(sum, 1+2+3+4);

Hope that helps!

2
  • I agree that this is a way to express the same code, and in a more clear way. But my question is if the &Some(_) in the 'pat' section of the for loop gives meaning. It would be a short-hand for what you suggested.
    – havardh
    May 24, 2014 at 1:46
  • I am not 100% sure about this as I am still learning rust: The pat is the pattern that rust tries to match to. This match must be exhaustive for your code to compile. This ensures no errors. For the option case however, I can see something like could be used shorthand. I am guessing a macro of some kind could create something similar, but I am unsure. Hope that helps.
    – luke
    May 24, 2014 at 2:04
1

for is binding each element in a to the pattern &Some(x) — so when the first element of a is &Some(1), x becomes 1. But None doesn't match the pattern &Some(x) so the binding can't succeed. Rust infers from the literal values that the type of a is actually Option (the type that encompasses either Some(_) or None) and that your pattern doesn't cover all of the possibilities. Instead of waiting for runtime to tell you it doesn't know what to do, it throws an error at compile-time instead.

From what little Rust I know (mostly having read the tutorial) I think you need to do something like:

for &thing in a.iter() {
    match thing {
        Some(x) => sum += x
        None => /* do nothing */
    }
}
1

The following works as well:

use std::iter::AdditiveIterator;

fn main() {

    let a = &[Some(1), Some(2), Some(3), None, Some(4)];
    let sum = a.iter().filter_map(|x| *x).sum();
    assert_eq!(sum, 1+2+3+4);
}
1

This also works:

let sum = a.iter().fold(0, |s, e| s + e.unwrap_or(0));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.