In Rust, what is the best way to print something b

2019-06-23 21:34发布

问题:

I want to print every item in a vector separated by commas. You could use numeric indexing:

for i in 0..vec.len() {
    print!("{}", vec[i]);
    if i < vec.len() - 1 {
        print!(", ");
    }
}

But what if you just have an Iterator? You either need to treat the first or last value specially, or create a custom iterator, which seems like a lot of work.

Is there a cleaner idiomatic way of expressing this in Rust?

回答1:

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


回答2:

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
});


回答3:

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>"));


标签: rust