Skip to main content

How to Join a Vec of Strings in Rust with join

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

roles.join(", ") joins the strings of a Vec into one String, with the separator between each pair: editor, viewer, admin. The separator is a string in double quotes, and the items have to be strings too.

Syntax​

Syntax
let <text>: String = <strings>.join(<separator>);
PartWhat it does
<strings>A Vec or an array of strings, either &str or String.
<separator>A string in double quotes, such as ", ", put between each pair of items. "" puts nothing between them.
The resultA new String. The Vec doesn't change.

The standard library documents join on slices: "Flattens a slice of T into a single value Self::Output, placing a given separator between each." Its example joins ["hello", "world"] with " " into "hello world", and the example below calls it on a Vec the same way.

The Example​

The example joins a Vec of three roles in three ways: with a comma and a space, with a bar between spaces, and with nothing between. Then a changed version tries to join a Vec of numbers.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which makes a Vec of the roles editor, viewer and admin and prints them joined with a comma and a space, with a bar between spaces, and with an empty separator.

src/main.rs
fn main() {
let roles = vec!["editor", "viewer", "admin"];

println!("{}", roles.join(", "));
println!("{}", roles.join(" | "));
println!("{}", roles.join(""));
}
  • roles.join(", ") puts a comma and a space between the roles.
  • roles.join(" | ") puts a bar with a space on each side.
  • roles.join("") puts nothing between them.

Step 2: Run It​

Terminal
cargo run -q
Output
editor, viewer, admin
editor | viewer | admin
editorvieweradmin

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Join a Vec of Numbers​

Replace src/main.rs with a version that also joins a Vec of scores:

src/main.rs
fn main() {
let roles = vec!["editor", "viewer", "admin"];

println!("{}", roles.join(", "));
println!("{}", roles.join(" | "));
println!("{}", roles.join(""));

let scores = vec![90, 75, 100];
println!("{}", scores.join(", "));
}
Terminal
cargo run -q
Output
error[E0599]: the method `join` exists for struct `Vec<{integer}>`, but its trait bounds were not satisfied
--> src/main.rs:9:27
|
9 | println!("{}", scores.join(", "));
| ^^^^ method cannot be called on `Vec<{integer}>` due to unsatisfied trait bounds
|
= note: the following trait bounds were not satisfied:
`[{integer}]: Join<_>`

For more information about this error, try `rustc --explain E0599`.
error: could not compile `demo` (bin "demo") due to 1 previous error

A zsh terminal where cargo run -q prints editor, viewer, admin with commas, then with bars, then run together, and then, for the changed file, fails with error E0599, the method join exists for a Vec of integers, but its trait bounds were not satisfied.

What Happened​

  • editor, viewer, admin: the separator went between each pair of roles, not after the last one.
  • editor | viewer | admin: any text can be the separator.
  • editorvieweradmin: an empty separator joins the roles with nothing between. concat did the same in my check.
  • The changed version didn't compile. join needs items it knows how to join, and the note lists the missing piece: `[{integer}]: Join<_>`. The Join trait is what join uses, and its page lists what it can join: strings, OsStr strings and slices. Numbers aren't any of them.

To join numbers, turn them into strings first. In my check, let text: Vec<String> = scores.iter().map(|n| n.to_string()).collect(); followed by text.join(", ") gave 90, 75, 100.

Common Mistakes​

MistakeWhat happensDo this instead
A separator in single quotes, as in join(',')expected `&str`, found `char`Write it in double quotes, join(","), as shown in this fix
A separator of several characters in single quotes, as in join(', ')error: character literal may only contain one codepointWrite it in double quotes, join(", "), as shown in this fix
join on an iterator, as in roles.iter().join(", ")error[E0599]: no method named `join` found for struct `std::slice::Iter<'a, T>` in the current scopeCall join on the Vec itself
connect, the old name of joinwarning: use of deprecated method `std::slice::<impl [T]>::connect`: renamed to joinUse join

Troubleshooting​

SymptomLikely causeFix
the method `join` exists for struct `Vec<{integer}>`, but its trait bounds were not satisfiedThe Vec holds numbersTurn them into strings first, with map(|n| n.to_string()) and collect()

FAQ​

What does join give for an empty Vec?​

An empty String. Joining an empty Vec<&str> with ", " printed nothing between the brackets I put around the result, []. A Vec with one item gave just that item, editor, with no separator.

Does join work on a Vec of String?​

Yes. A Vec<String> holding editor and viewer, joined with ", ", gave editor, viewer.

Conclusion​

join turns a Vec of strings into one String, with a separator in double quotes between each pair. Turn numbers or other values into strings first, and call join on the Vec, not on an iterator.

Additional Resources​

  • join and concat, in the Rust standard library documentation.
  • Join, the trait that lists what join can join.