#join #string #iterator #separator #items #io #write


A python-like way to join items in an iterator with a separator

3 releases

0.1.2 Feb 11, 2021
0.1.1 Feb 9, 2021
0.1.0 Feb 9, 2021

#1272 in Rust patterns

Download history 23/week @ 2024-03-24 65/week @ 2024-03-31 18/week @ 2024-04-07 18/week @ 2024-04-14 26/week @ 2024-04-21 25/week @ 2024-04-28 22/week @ 2024-05-05 22/week @ 2024-05-12 22/week @ 2024-05-19 40/week @ 2024-05-26 25/week @ 2024-06-02 18/week @ 2024-06-09 23/week @ 2024-06-16 15/week @ 2024-06-23 10/week @ 2024-06-30 2/week @ 2024-07-07

52 downloads per month
Used in 4 crates (3 directly)


168 lines

String join

A helper trait for joining an iterator by a string-like thing using a python-like syntax


use string_join::Join

"=>".join(["a", "b"].iter().cycle().take(5)); // => "a=>b=>a=>b=>a"
" ".join(&["a", "b", "c"]); // => "a b c"

let mut f = File::write("foo.txt").unwrap();
"\n".write_join(&mut f, &["a", "b", "c"]); // std::io::Result<5> (writes joined string to writer and returns a result
                                           // with either the number of bytes written, or a std::io::Error


String join

Uses a python-like syntax to join any iterator-like thing with any string-like thing


use string_join::Join;

assert_eq!("=".join(&["a", "b", "c"]), String::from("a=b=c"));

You can also write a joined collection directly to an io::Writer

use std::fs::File;
use string_join::display::Join;

let mut f = File::create("foo.txt")?;
"\n".write_join(&mut f, &['a', 'b', 'c'])?; // => writes `a\nb\nc` to the writer and returns
                                            //    the number of bytes written (5, in this case)

AsRef<str> vs Display

There are two ways to convert items in a collection to a joined string. If all the items, as well as the separator, implement AsRef<str>, then we only have to allocate a single string and can write bytes into it. However, this limits the types that we can join. If we instead limit the types we can join to types that implement Display, we can join a lot more types, with the tradeoff that a lot more allocations will be happening.

Therefore, there are two modules in this crate, string_join::as_ref and string_join::display. They both provide a trait called Join and both the traits have methods write_join and join. However, one is implemented for AsRef<str> types and one for Display types. This way, the user of the crate can decide which implementation they want to use.

To keep backwards compatibility, string_join::Join is the same as string_join::as_ref::Join.

No runtime deps