How to Join a Vector of Strings in Rust

Use the `join` method on a `&[String]` or `&[&str]` slice, passing the desired separator as an argument.

Use the join method on a &[String] or &[&str] slice, passing the desired separator as an argument. This method returns a new String containing all elements concatenated with the separator between them.

For a vector of owned String values, you can call join directly on a slice of the vector. If your vector contains string slices (&str), the method works identically.

fn main() {
    // Vector of owned Strings
    let words: Vec<String> = vec!["Rust".to_string(), "is", "great".to_string()];
    let sentence = words.join(" ");
    println!("{}", sentence); // Output: Rust is great

    // Vector of string slices
    let parts: Vec<&str> = vec!["hello", "world", "rust"];
    let combined = parts.join("-");
    println!("{}", combined); // Output: hello-world-rust
}

If you need to join a vector of String without cloning or moving ownership unnecessarily, remember that join borrows the slice (&[String]), so it doesn't consume the original vector. This allows you to reuse the vector afterward.

fn main() {
    let mut items = vec!["apple".to_string(), "banana".to_string(), "cherry".to_string()];
    
    // Join without consuming the vector
    let result = items.join(", ");
    println!("Joined: {}", result);
    
    // The original vector is still available
    println!("Original count: {}", items.len()); 
}

For performance-critical scenarios where you are joining a large number of strings, join is generally efficient as it pre-calculates the required capacity. However, if you are building the string incrementally in a loop, using String::with_capacity and push_str might offer more control, though join remains the idiomatic and readable choice for most cases.

If your collection is not a Vec but another type that implements IntoIterator (like a VecDeque or a slice), you can convert it to a slice or use join on the slice directly, as the method is defined on slices, not just vectors.

fn main() {
    let data = vec!["a".to_string(), "b".to_string()];
    // Works on a slice of the vector
    let s = data[..].join(" ");
    
    // Works on a slice of string literals
    let literals = ["x", "y", "z"];
    let s2 = literals.join(":");
}