In Rust, what is the best way to print something between each value in a container?

If you want to avoid using a variable to check if element is first, you can make use of .take() and .skip() methods of iterators:

for e in vec.iter().take(1) {
    print!("{}", e);
}
for e in vec.iter().skip(1) {
    print!(", {}", e);
}

or compact all in a fold :

vec.iter().fold(true, |first, elem| {
    if !first { print(", "); }
    print(elem);
    false
});

let first = true;
for item in iterator {
    if !first {
        print(", ");
    }
    print(item);
    first = false;
}

You can do something special for the first element, then treat all subsequent ones the same:

let mut iter = vec.iter();
if let Some(item) = iter.next() {
    print!("{}", item);

    for item in iter {
        print!("<separator>{}", item);        
    }
}

If you use Itertools::format, it's even easier:

println!("{}", vec.iter().format("<separator>"));

Tags:

Rust