Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a `connect()` implementation for `Iterator<Item=Str>`? [duplicate]

Tags:

rust

Currently the SliceConcatExt seems to be very specifically crafted for slices or vectors of Strings, even though it arbitrarily constrains its use. That particular use-case is reflected in the trait name as well, after all, it is called SliceConcatExt for a reason.

Is there a more general connect() implementation which would take any Iterator over items supporting the Str trait ?. If not, are there any plans to remedy this ?

Example

use std::iter::IntoIterator;

fn connected<S, I>(s: I) -> String
where S: Str,
      I: IntoIterator<Item=S> {
    // have
    s.into_iter().collect::<Vec<S>>().connect(", ")

    // want
    // s.into_iter().connect(", ")
    // error: type `<I as core::iter::IntoIterator>::IntoIter` does not implement any method in scope named `connect`
    // tests/lang.rs:790         s.into_iter().connect(", ")
}

connected(&["foo", "bar"]);

One could possibly implement SliceConcatExt for any iterator with item type Str, but I have the suspicion that connect() currently is just unnecessarily specialized, which might be fixable until Rust beta.

Using rustc 1.0.0-nightly (522d09dfe 2015-02-19) (built 2015-02-19)

like image 227
Byron Avatar asked Sep 29 '22 16:09

Byron


1 Answers

The closest solution I know of would be to use Itertools::intersperse:

#![feature(core)]

extern crate itertools;

use std::iter::IntoIterator;
use itertools::Itertools;

fn connected<'a, S, I>(s: I) -> String //'
    where S: Str,
          I: IntoIterator<Item=&'a S> //'
{
    s.into_iter().map(|s| s.as_slice()).intersperse(", ").collect()
}

fn main() {
    println!("{}", connected(&["foo", "bar"]));
}
like image 115
Shepmaster Avatar answered Nov 11 '22 19:11

Shepmaster