HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
theoverstringsequivalentvectorjoinoperatorwhat

Problem

I wasn't able to find the Rust equivalent for the "join" operator over a vector of Strings. I have a Vec 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:

  • What's an idiomatic way to print an iterator separated by spaces in Rust?

Solution

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.

join copies elements of the vector, it does not move them, thus it preserves the contents of the vector, rather than destroying it.

Code Snippets

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

Context

Stack Overflow Q#28311868, score: 408

Revisions (0)

No revisions yet.