What is the equivalent of the join operator over a vector of Strings?

StringRust

String Problem Overview


I wasn't able to find the Rust equivalent for the "join" operator over a vector of Strings. I have a Vec<String> and I'd like to join them as a single String:

let string_list = vec!["Foo".to_string(),"Bar".to_string()];
let joined = something::join(string_list,"-");
assert_eq!("Foo-Bar", joined);

Related:

String Solutions


Solution 1 - String

In Rust 1.3.0 and later, join is available:

fn main() {
    let string_list = vec!["Foo".to_string(),"Bar".to_string()];
    let joined = string_list.join("-");
    assert_eq!("Foo-Bar", joined);
}

Before 1.3.0 this method was called connect:

let joined = string_list.connect("-");

Note that you do not need to import anything since the methods are automatically imported by the standard library prelude.

Solution 2 - String

As mentioned by Wilfred, SliceConcatExt::connect has been deprecated since version 1.3.0 in favour of SliceConcatExt::join:

let joined = string_list.join("-");

Solution 3 - String

There is a function from the itertools crate also called join which joins an iterator:

extern crate itertools; // 0.7.8

use itertools::free::join;
use std::fmt;

pub struct MyScores {
    scores: Vec<i16>,
}

impl fmt::Display for MyScores {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str("MyScores(")?;
        fmt.write_str(&join(&self.scores[..], &","))?;
        fmt.write_str(")")?;
        Ok(())
    }
}

fn main() {
    let my_scores = MyScores {
        scores: vec![12, 23, 34, 45],
    };
    println!("{}", my_scores); // outputs MyScores(12,23,34,45)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavide AversaView Question on Stackoverflow
Solution 1 - StringMatthewGView Answer on Stackoverflow
Solution 2 - StringDanilo BargenView Answer on Stackoverflow
Solution 3 - StringNick LinkerView Answer on Stackoverflow