Hi,
Im trying to use values_of, but every example uses unwrap().collect() but in my case unwrap can fail:
if matches.is_present("patterns") {
let patterns = matches.values_of("patterns").unwrap().collect();
let paths = matches.values_of("paths").unwrap_or("./").collect(); //error
// more code ...
}
I need to get the values of paths or default to "./".
I see, the allocation only occurs when the closure is called if the unwrap is successful then there is no need for the closure and therefore for the allocation.
Thanks!!!
Sorry, thinks that I was looking at something wrong.
You already do this by using collect, you just need to move this operation before the unwrap:
if matches.is_present("patterns") {
let patterns: Vec<_> = matches.values_of("patterns").unwrap().collect();
let paths = matches
.values_of("paths")
.map(Values::collect) // or Iterator::collect
.unwrap_or_else(|| vec![]);
}
Thanks for the answer!!!!
Could you please explain me the solution or point me to where i can read something about that? values_of returns an option that wraps a clap::Value type, right?
Is posible to iterate over an option type? What it does, to the option type?
Thanks again
map in this case is not an iteration, strictly speaking, since Option hold only one item and not a sequence of items. It's more like the functor mapping: given a function from T1 to T2 and an instance of Functor<T1>, convert it to Functor<T2>. If you're not familiar with this kind of thing, just think of it as something which let us run a function (in this case - Values::collect, or equivalently - |val| val.collect()) inside the Option, without unwrapping it.
By the way, if you want to learn more about Option/Result combinators, here's a good interactive cheatsheet.