I am concatenating several items in vec, manually into string for viewing, like [a, b, c].
let iter = vec.iter(); // vec is &Vec, not mutable
let mut str = String::new();
str.push_str("[");
while let Some(v) = iter.next() {
str.push_str(&v.str());
str.push_str(", ");
}
str.push_str("]");
So I got [a, b, c, ]. It is troublesome to detect the length and to remove the ending comma. Is there any easy way for this?
While your actual question has been answered, note that in your example, if you treat the first (rather than last) item as special, you can make the whole thing more efficient by avoiding the check alltoghether.
let mut iter = vec.iter();
let mut str = String::new();
str.push('[');
if let Some(first) = iter.next() {
str.push_str(first);
}
while let Some(next) = iter.next() {
str.push_str(", ");
str.push_str(next)
}
str.push(']');
str