Regex capture iterator method moves iterator -


i processing simple strings of format "1s:1d", "100:5000", etc regex:

let retention_matcher = regex::regex::new({r"^(\d+)([smhdy])?:(\d+)([smhdy])?$"}).unwrap(); 

i know regex should match once want run regex captures , check number of captures.

    let iter = retention_matcher.captures_iter(ts);     let count = iter.count();     println!("iter.count(): {}", count);      let _ : vec<option<(u64,u64)>> = iter.map(|regex_match| {         let retval = retention_spec_to_pair(regex_match);         println!("precision_opt: {:?}", retval);         retval     }).collect(); 

the issue count() method moves iter , can no longer use it.

src/bin/whisper.rs:147:42: 147:46 error: use of moved value: `iter` src/bin/whisper.rs:147         let _ : vec<option<(u64,u64)>> = iter.map(|regex_match| {                                                                 ^~~~ src/bin/whisper.rs:144:21: 144:25 note: `iter` moved here because has type `regex::re::findcaptures<'_, '_>`, non-copyable src/bin/whisper.rs:144         let count = iter.count(); 

this not make sense me. should count method return copyable usize value , not move iter? how can work around issue?

i suspect you're thinking of iter being abstract sequence of captures. more accurate think of representing position within abstract sequence of captures. basic thing iterator knows advance next item in sequence; is, can advance position , next element in sequence.

count moves iter because in order count how many elements in sequence, has generate whole sequence. necessarily modifies iterator stepping through whole sequence. moves because after calling count, iterator isn't useful more. definition, must past end of sequence!

sadly, doesn't iterator type in question (findcaptures) clone, can't make copy of it.

the solution restructure code not call count. if want first element , ensure there no more, simplest pattern be:

let mut iter = ...; if let some(regex_match) = iter.next() {     // ensure there no next element.     assert_eq!(iter.next(), none);      // process regex_match ... } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -