Include `collect_vec` in `std`?

A common example:

fn foo(s: &[u8]) { ... }

fn main() {
    let v = (0..128).collect();
    foo(&v);
}
error[E0277]: the trait bound `[u8]: std::marker::Sized` is not satisfied
 --> src/main.rs:4:9
  |
4 |     let v = (0..128).collect();
  |         ^ `[u8]` does not have a constant size known at compile-time
  |
  = help: the trait `std::marker::Sized` is not implemented for `[u8]`
  = note: all local variables must have a statically known size

error[E0277]: the trait bound `[u8]: std::iter::FromIterator<{integer}>` is not satisfied
 --> src/main.rs:4:22
  |
4 |     let v = (0..128).collect();
  |                      ^^^^^^^ a collection of type `[u8]` cannot be built from an iterator over elements of type `{integer}`
  |
  = help: the trait `std::iter::FromIterator<{integer}>` is not implemented for `[u8]`
4 Likes

Iā€™ve been using the Turbofish quite a few times recently. One example is testing functions which return an iterator, where for testing the complete output itā€™s easiest to compare against a Vec (seems like type inference should work here, but it wasnā€™t); also in case the iterator output must be used multiple times and the iterator cannot be cloned then the output must be collected.


It seems like thereā€™s quite a bit of support for adding Iterator::into_vec, but as pointed out this isnā€™t possible.

An alternative is to add a trait like trait IntoVec { type T; fn into_vec(self) -> Vec<T>; }, but adding a trait just for this seems unreasonable.

Another possibility: Vec::collect_from(iter).

Or maybe we just have to accept that adding this isnā€™t reasonable? :frowning:

1 Like

Do you mean

use std::iter::FromIterator;
Vec::from_iter(iter);

I'm still not sure if Editions can add new traits to the prelude, maybe FromIterator could be included in Edition 2018? Checking github it was briefly mentioned in Add an extended prelude for the 2018 editions by SimonSapin Ā· Pull Request #51434 Ā· rust-lang/rust Ā· GitHub

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.