foreach - Why does `Option` support `IntoIterator`? -


i trying iterate on subsection of vector of strings, i.e. subslice of vec<string>. within each iteration, wanted pass string slice function.

i didn't notice vec::get returns option, , thought directly iterate on return value:

fn take_str(s: &str) {     println!("{}", s); }  fn main() {     let str_vec: vec<string> =         ["one", "two", "three", "uno", "dos", "tres"].iter().map(|&s|          s.into()).collect();     s in str_vec.get(0..3) {         take_str(&s); // type mismatch: found type `&&[std::string::string]`     } } 

clearly, expecting s string, it's &[string]. because loop iterating on option returned vec::get().

i wrote following code, demonstrates for loop in fact unwrapping option:

let foo = option::some ( ["foo".to_string()] ); f in foo {     take_str(&f); // same error above, showing `f` of type `&[string]` } 

but incredibly confusing; never expected (until wrote code , figured out it's doing) option unwrapped iterating on it. why supported? use case there iterating on option?

what use case there iterating on option?

my favorite reason, in word, flat_map:

fn main() {     let results = vec![some(1), none, some(3), none];     let sum: i32 = results.into_iter().flat_map(|x| x).sum();     println!("{}", sum) } 

option can thought of container can hold 0 or 1 elements. compare vec, can hold 0 or many elements. in large set of ways, option is container vec!

implementing intoiterator allows option participate in larger share of apis.

note intoiterator also implemented result, similar reasons.

but incredibly confusing

yes, is, why clippy has lint it:

warning: loop on `str_vec.get(0..3)`, `option`.          more readably written `if let` statement. 

this shows there ways option not container programmer.


Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -