Can & Some (_) in vec.iter () {..}?

I tried to execute 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:

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 compiler for the for loop without using the matching expression suggested by luke and hobbs? Or is this error message misleading? This does not seem to be given by the grammatical definition of for.

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

I am:

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" part for_expr? This is not specified in http://doc.rust-lang.org/rust.html#for-expressions , unlike the definition in http://doc.rust-lang.org/rust.html#match-expressions .

+4
source share
5 answers

for, , , let: , .. .

&, , . (, ) , , , .

for , desugars ( desugars , , , rustc --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> }
            }
        }
    }
}

match, .. ( ), , <pattern> &Some(_), Some(&None) .

( Some Some(value) => { let <pattern> = value; .... , desugaring, : # 14390.)

+3

Some - . Option : Some(T) None. , a.iter() Some(T) None. , match. - :

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);

, !

+1

for a &Some(x) - , a &Some(1), x 1. None pattern &Some(x), . Rust , a Option (, Some(_), None), . , , , , , .

Rust ( , ), , - :

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

:

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

:

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

Source: https://habr.com/ru/post/1541840/


All Articles