Reputation: 23
here I am splitting vec into sub-vectors of equal size 4 and then returning a collection, I want the type returned from the collection to be Vec<String>
. How can I do so?
let mut split_operations : Vec<String> = vec[2..].chunks(4).collect::<String>();
This generates the following error:
a value of type std::string::String
cannot be built from an iterator over elements of type &[std::string::String]
value of type std::string::String
cannot be built from std::iter::Iterator<Item=&[std::string::String]>
help: the trait std::iter::FromIterator<&[std::string::String]>
is not implemented for std::string::String
rustc(E0277)
Upvotes: 2
Views: 1345
Reputation: 42492
The type parameter of collect()
is what the entire thing should be collected to. So the parameter to collect
and the actual type are redundant, only one is needed.
However Rust doesn't want to guess how or what to the chunks
are supposed to change: here you have an iterator of slices (Iterator<Item=&[String]
). You can collect an Iterator<Item=String>
to a Vec<String>
or to a single String
(it'll join all the items), but the intermediate slice means Rust's got no idea what's supposed to happen.
If you want each chunk to become a single string, you need to do that explicitely in a map
e.g.
let mut split_operations : Vec<String> = vec[2..].chunks(4)
.map(|c| c.concat())
.collect();
If you want to play (and / or infuriate your colleagues), you can also write the map callback as <[_]>::concat
.
Upvotes: 6